2016-08-15 22 views
1
class Person { 
    private var privateAge = 0 
    def age() = {privateAge} 
    def age_=(age:Int) {privateAge=age} 
} 

object Main{ 
    def main(args:Array[String]){ 
    val p = new Person 
    p.age = 12 
    } 
} 

當編譯,p.age = 12加薪問題:重新分配到VAL斯卡拉:方法與括號diffenence而不是

雖然如果我刪除的def age() = {privateAge}括號中的Person類,它工作正常。

我很困惑,p.age = 12方法應該對應於def age_=(age:Int) {privateAge=age},但爲什麼我改變了def age() = {privateAge},它的工作原理。

+0

[使用閃避,VAL和var Scala中的(可能的重複http://stackoverflow.com/問題/ 4437373/def-val-and-var-in-scala) –

回答

2

您不能定義僅限制setter的屬性。 Scala only recognizes a setter when it is paired with a corresponding getter。 getter是沒有參數列表的方法,setter是一個名字以_=結尾的方法,它帶有一個參數列表,該參數列表取得getter方法的返回類型的單個參數並返回Unit

在你的代碼中,你沒有getter方法:age不是一個getter,因爲它有一個參數列表。注意:一個空的參數列表與不參數列表是一樣的,就像空房子與沒有房子一樣。

0

這是怎麼定製分配在規範中定義:

如果x在某些模板中定義的參數的功能,同樣的模板中包含的成員,則分配x = e解釋setter函數x_=作爲該設置函數的調用x_=(e)。類似地,對無參數功能x的分配f.x = e被解釋爲調用f.x_=(e)

(從http://scala-lang.org/files/archive/spec/2.11/06-expressions.html#assignments

「無參數」 的方法在這裏定義:http://www.scala-lang.org/files/archive/spec/2.11/03-types.html#method-types

+0

不,對於「無參數」請參見http://www.scala-lang.org/files/archive/spec/2.11/03- types.html#方法類型和其他答案。 –

+1

太棒了,我會更新 – handler

+0

你能否解釋爲什麼如果在age()中使用圓括號,爲什麼會出現「重新分配到val」的錯誤?是否因爲age()返回privateAge的值,所以int值不能被重新分配給另一個int值? – Samar