Reputation: 53826
I'm trying to understand the add method in below class taken from book 'Programming in Scala - Second Edition'. Is this correct : The method 'add' takes defines an operator which of type Rational. I don't know what is occurring within the new Rational :
numer * that.denom + that.numer * denom,
denom * that.denom
How are numer & denom be assigned here ? , Why is each expression separated by a comma ? Entire class :
class Rational(n: Int , d: Int) {
require(d != 0)
private val g = gcd(n.abs, d.abs)
val numer = n / g
val denom = d/ g
def this(n: Int) = this(n, 1)
def add(that: Rational): Rational =
new Rational(
numer * that.denom + that.numer * denom,
denom * that.denom
)
override def toString = numer +"/" + denom
private def gcd(a: Int, b: Int): Int =
if(b == 0) a else gcd(b, a % b)
}
Upvotes: 2
Views: 84
Reputation: 9364
That two expressions are the arguments to the Rational
constructor, thus they will be the private val
s n
and d
respectively. For example
class C(a: Int, b: Int)
val c1 = new C(1, 2) // here 1, 2 is like the two expressions you mention
The add
method implements rational number addition:
a c a*d c*b a*d + c*b
--- + --- = ----- + ----- = -----------
b d b*d b*d b*d
where
a = numer
b = denom
c = that.numer
d = that.denom
Upvotes: 4