我想澄清斯卡拉Scala的構造函數參數修飾符
class Test(a:Int) {
def print = println(a)
}
class Test1(val a:Int) {
def print = println(a)
}
class Test2(private val a:Int) {
def print = println(a)
}
val test = new Test(1)
val test1 = new Test1(1)
val test2 = new Test2(1)
一些概念現在,當我試圖訪問一個測試,TEST1,TEST2。
斯卡拉打印
scala> test.a
<console>:11: error: value a is not a member of Test
scala> test1.a
res5: Int = 1
scala> test2.a
<console>:10: error: value a cannot be accessed in Test2
我明白了一個整數Test1的是和TEST2的領域。但Integer a和class Test有什麼關係?顯然整數a不是Test類的字段,但它在打印函數中是可訪問的。
沒有'val'(或其他註釋),構造函數參數的行爲就像一個對所有嵌套的作用域都可見的函數參數。 (我不確定當前實現中發生了什麼奇妙的事情,但是我想象一個名字被破壞的字段。請看一下生成的Java類。) – 2012-12-26 22:59:41