快学Scala(Second Edition)第6章(对象)习题详解

1. 第一题

代码:

object Conversions {

    def inchesToCentimeters(inches: Double): Double = {
      inches * 2.54
    }

    //英制加仑
    def gallonsToLiters(gallons: Double): Double = {
      gallons * 4.5460919
    }

    def milesToKilometers(miles: Double): Double = {
      miles * 1.609344
    }
}

测试代码:

Conversions.inchesToCentimeters(2)
Conversions.gallonsToLiters(3.5)
Conversions.milesToKilometers(5)

2. 第二题

代码:

abstract class UnitConversion {
    def convert(x: Double): Double
  }

  object InchesToCentimeters extends UnitConversion {
    override def convert(x: Double): Double = {
      x * 2.54
    }
  }

  object GallonsToLiters extends UnitConversion {
    override def convert(x: Double): Double = {
      x * 4.5460919
    }
  }

  object MilesToKilometers extends UnitConversion {
    override def convert(x: Double): Double = {
      x * 1.609344
    }
}

测试代码:

InchesToCentimeters.convert(2)
GallonsToLiters.convert(5)
MilesToKilometers.convert(6)

3. 第三题

不懂

4. 第四题

代码:

class Point(var x: Double, var y: Double) {
    def this() {
      this(0, 0)
    }
  }

object Point {
    def apply(x: Double, y: Double): Point = new Point(x, y)
}

测试代码:

var point = Point(2, 3)
point.x
point.y

5. 第五题

代码:

object Reverse extends App {
    Console.println(s"${args.reverse mkString " "}")
}

6. 第六题

代码:

object PokerSuit extends Enumeration {

    val Plum = Value(0, "♣️")
    val Diamonds = Value("♦️")
    val Heart = Value("♥️")
    val Spade = Value("♠️")

}

测试代码:

PokerSuit.Heart.toString

7. 第七题

代码(接上一题):

def cardIsRed(suit: String): Boolean = {
    if (PokerSuit.Diamonds.toString == suit || PokerSuit.Heart.toString == suit) true
    else false
}

测试代码:

cardIsRed("♣")
cardIsRed("♥️")

8. 第八题

你可能感兴趣的:(快学Scala(Second Edition)第6章(对象)习题详解)