The Artima Developer Community
Sponsored Link

Programming in Scala Forum
PDF pages 448-449

1 reply on 1 page. Most recent reply: Jun 25, 2016 4:15 PM by Jack Kelley

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Jack Kelley

Posts: 2
Nickname: 100514
Registered: Jun, 2016

PDF pages 448-449 Posted: Jun 25, 2016 9:23 AM
Reply to this message Reply
Advertisement
There is something confusing on page 448.

"with some numerator and denominator expressions that are not simple literals" seems unnecessary here (in the context of Listing 20.4 on page 449).

I have posted a suggestion for page 448 (which includes my own transcript).


Jack Kelley

Posts: 2
Nickname: 100514
Registered: Jun, 2016

Re: PDF pages 448-449 Posted: Jun 25, 2016 4:15 PM
Reply to this message Reply
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>

Flat View: This topic has 1 reply on 1 page
Topic: Where is my book Previous Topic   Next Topic Topic: Type alias

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use