Jack Kelley
Posts: 2
Nickname: 100514
Registered: Jun, 2016
|
|
Re: PDF pages 448-449
|
Posted: Jun 25, 2016 4:15 PM
|
|
The following transcript shows more clearly what is happening (up to Listing 20.5 on page 450):
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_92). Type in expressions for evaluation. Or try :help.
scala> trait RationalTrait { | val numerArg: Int | val denomArg: Int | } defined trait RationalTrait
scala>
scala> new RationalTrait { | val numerArg = 1 | val denomArg = 2 | } res0: RationalTrait = $anon$1@5a9f4771
scala>
scala> val x = 2 x: Int = 2
scala>
scala> new RationalTrait { | val numerArg = 1 * x | val denomArg = 2 * x | } res1: RationalTrait = $anon$1@15713d56
scala>
scala> trait RationalTrait { | val numerArg: Int | val denomArg: Int | require(denomArg != 0) | private val g = gcd(numerArg, denomArg) | val numer = numerArg / g | val denom = denomArg / g | private def gcd(a: Int, b: Int): Int = | if (b == 0) a else gcd(b, a % b) | override def toString = numer + "/" + denom | } defined trait RationalTrait
scala>
scala> new RationalTrait { | val numerArg = 1 | val denomArg = 2 | } java.lang.IllegalArgumentException: requirement failed at scala.Predef$.require(Predef.scala:212) at RationalTrait$class.$init$(<console>:14) ... 36 elided
scala>
scala> new RationalTrait { | val numerArg = 1 * x | val denomArg = 2 * x | } java.lang.IllegalArgumentException: requirement failed at scala.Predef$.require(Predef.scala:212) at RationalTrait$class.$init$(<console>:14) ... 36 elided
scala>
scala> new { | val numerArg = 1 | val denomArg = 2 | } with RationalTrait res4: RationalTrait = 1/2
scala>
scala> new { | val numerArg = 1 * x | val denomArg = 2 * x | } with RationalTrait res5: RationalTrait = 1/2
scala>
|
|