2012-09-13 33 views
2

我想了解從書「在Scala編程 - 第二版」採取以下類的add方法中。 這是正確的: 「添加」拍攝的方法,定義哪些類型的理性的操作者。我不知道什麼是內新的Rational發生:不確定的方法是如何工作的斯卡拉類

numer * that.denom + that.numer * denom, 
denom * that.denom 

是如何NUMER & DENOM在這裏分配?爲什麼每個表達式用逗號分隔? 整個類:

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) 
} 

回答

4

這兩個表達式是參數的構造函數Rational,因此,他們將分別是private val小號nd。例如

class C(a: Int, b: Int) 
val c1 = new C(1, 2) // here 1, 2 is like the two expressions you mention 

add方法實現有理數此外:

a  c  a*d  c*b  a*d + c*b 
--- + --- = ----- + ----- = ----------- 
b  d  b*d  b*d  b*d 

其中

a = numer 
b = denom 
c = that.numer 
d = that.denom