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)
}
That two expressions are the arguments to the
Rationalconstructor, thus they will be theprivate valsnanddrespectively. For exampleThe
addmethod implements rational number addition:where