/** * 1. Write an object Conversions with methods inchesToCentimeters, gallonsToLiters, and milesToKilometers. */ scala> object Conversions { | def inchesToCentimeters(inches: Double): Double = 2.54 * inches | def gallonsToLiters(gallons: Double): Double = 3.78541 * gallons | def milesToKilometers(miles: Double): Double = 1.61 * miles | } defined object Conversions scala> Conversions.inchesToCentimeters(10) res56: Double = 25.4 scala> Conversions.gallonsToLiters(1) res57: Double = 3.78541 scala> Conversions.milesToKilometers(7) res58: Double = 11.270000000000001 /** * 2. The preceding problem wasn’t very object-oriented. Provide a general superclass UnitConversion and define objects InchesToCentimeters, * GallonsToLiters, and MilesToKilometers that extend it. */ scala> abstract class UnitConversion { | def convert(input: Double): Double | } defined class UnitConversion scala> object InchesToCentimeters extends UnitConversion { | def convert(input: Double) = 2.54 * input | def apply(input: Double) = convert(input) | } defined object InchesToCentimeters scala> InchesToCentimeters(1) res59: Double = 2.54 scala> InchesToCentimeters(10) res60: Double = 25.4 /** * 3. Define an Origin object that extends java.awt.Point. * Why is this not actually a good idea? (Have a close look at the methods of the Point class.) */ // Not a good idea since it has setXXX methods and in singleton since everybody shares, anyone can // change value causing trouble /** * 4. Define a Point class with a companion object so that you can construct * Point instances as Point(3, 4), without using new. */ scala> :paste // Entering paste mode (ctrl-D to finish) object Point { def apply(x: Int, y: Int) = new Point(x,y) } class Point private(x:Int, y: Int) { override def toString = s"New Point Created (${x}, ${y}))" } // Exiting paste mode, now interpreting. defined object Point defined class Point scala> Point(3,4) res0: Point = New Point Created (3, 4)) /** * 5. Write a Scala application, using the App trait, that prints the command-line arguments * in reverse order, separated by spaces. For example, scala Reverse Hello World should print World Hello.” */ // Open a new file called MyApp.scala and paste the following contents object MyApp extends App { if(args.length < 1) println("Provide enough arguments to print") println(args.reverse.mkString(" ")) } $ scalac MyApp.scala $ scala MyApp Hello World Scala Scala World Hello $ scala MyApp Provide enough arguments to print // Not attempting 6,7,8 (Enumeration)