我來自Java背景,也是新的Scala,目前正在閱讀「Scala編程」一書。Scala:類參數訪問vs對象字段訪問
有書中如下的例子:
class Rational(n: Int, d: Int) { // This won't compile
require(d != 0)
override def toString = n + "/" + d
def add(that: Rational): Rational = new Rational(n * that.d + that.n * d, d * that.d)
}
然而,鑑於此代碼的編譯器抱怨:
error: value d is not a member of Rational
new Rational(n * that.d + that.n * d, d * that.d)
^
error: value n is not a member of Rational
new Rational(n * that.d + that.n * d, d * that.d)
^
error: value d is not a member of Rational
new Rational(n * that.d + that.n * d, d * that.d)
^
解釋說:
儘管類參數n和d在您的add方法的代碼範圍內,您只能在調用add的對象上訪問它們的值。因此,當你在add的實現中說n或d時,編譯器很樂意爲你提供這些類參數的值。但它不會讓你說.n或that.d,因爲它沒有引用添加被調用的Rational對象。要訪問分子和分母,你需要將它們放入字段中。
也是一個正確的執行,給出如下:
class Rational(n: Int, d: Int) {
require(d != 0)
val numer: Int = n
val denom: Int = d
override def toString = numer + "/" + denom
def add(that: Rational): Rational =
new Rational(
numer * that.denom + that.numer * denom,
denom * that.denom
)
}
我試圖瞭解過很多次,但目前尚不清楚。
我已經在課堂上有n
和d
參數。我可以通過add
方法訪問它們。我將另一個Rational
對象傳遞給add
方法。它也應該有n
和d
,對吧?
that.n
和that.d
有什麼問題?爲什麼我需要在字段中使用參數?
此外,重寫的toString
方法只是簡單地採取n
和d
,這不會失敗嗎?
我可能聽起來很愚蠢,但在我前進之前,確實需要明確理解這一點,以獲得更好的基本面。