Created
December 30, 2020 16:23
-
-
Save Haaroon/0131a101ee4ffd3bd9cda9eac0914d20 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 1. Write an object Conversions with methods inchesToCentimeters, gallonsToLiters, and milesToKilometers. | |
object Conversions { | |
def inchesToCentimeters(value: Double)={ | |
// 1 inch = 2.54 | |
value * 2.54 | |
} | |
def gallonsToLiters(value: Double)={ | |
// 1 gallon = 3.78541 liters | |
value * 3.78541 | |
} | |
def milesToKilometers(value: Double)={ | |
// 1 mile = 1.60934 kms | |
value * 1.60934 | |
} | |
} | |
// 2. The preceding problem wasn’t very object-oriented. Provide a general super- class UnitConversion and define objects InchesToCentimeters, GallonsToLiters, and MilesToKilometers that extend it. | |
abstract class UnitConversion { | |
def convert(value: Double): Double | |
} | |
object inchesToCentimeters extends UnitConversion { | |
def convert(value: Double)={value * 2.54} | |
} | |
object gallonsToLiters extends UnitConversion { | |
def convert(value: Double)={value * 3.78541} | |
} | |
object milesToKilometers extends UnitConversion { | |
def convert(value: Double)={value * 1.60934} | |
} | |
// 4. Define a Point class with a companion object so that you can construct Point instances as Point(3, 4), without using new. | |
class Point private (val x: Int, val y: Int) { | |
} | |
object Point { | |
def apply(x: Int, y: Int) = new Point(x, y) | |
} | |
// 5. Write a Scala application, using the App trait, that prints its command-line arguments in reverse order, separated by spaces. For example, scala Reverse Hello World should print World Hello. | |
object reverseLine extends App { | |
for (arg <- args.reverse) print(arg + " ") | |
} | |
object cardColor extends Enumeration { | |
type cardColor = Value | |
val club = Value("♣") | |
val spade = Value("♠") | |
val diamond = Value("♦") | |
val heart = Value("♥") | |
} | |
object rgbColorCube extends Enumeration { | |
val black = Value(0x000000, "Black") | |
val white = Value(0xffffff, "White") | |
val red = Value(0xff0000, "Red") | |
val yellow = Value(0xffff00, "Yellow") | |
val green = Value(0x00ff00, "Green") | |
val blue = Value(0x0000ff, "Blue") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment