您的示例行爲與C,java,python或任何其他編程語言完全相同。
我想你真的在問val/var不可變/可變的區別。這裏有一個更清楚的例子:
class A(var s: String) {
override def toString = s
}
val x = new A("first") // a new A object [Object1] is allocated, x points to it
var y = x // y is pointed to x's referent, which is [Object1]
val z = y // z is pointed to y's referent, which is [Object1]
println(x) // "first"
println(y) // "first"
println(z) // "first"
y = new A("second") // a new A object [Object2] is allocated, y points to it
println(x) // "first" // note that x is still pointing to the same object [Object1]
println(y) // "second"
println(z) // "first" // so is z
x.s = "third" // the string *inside* [Object1] is changed
println(x) // "third" // x still points to [Object1], which now contains "third"
println(y) // "second" // y still points to [Object2]
println(z) // "third" // z still points to [Object1], which now contains "third"
說y =
總是會在一個新的對象指向y
,而不是當前對象改變y
點。這意味着說y =
永遠不會更改x
或z
。
如果A
是不可變的(class A(s: String)
),那麼唯一的區別是操作x.s =
將被禁止。上面的所有內容都完全一樣。
來源
2014-05-23 00:13:01
dhg
這不回答我的問題。 – Emil
查看我的更新。我做了一個新的例子,它實際上顯示了val/var和immutable/mutable之間的區別。 – dhg
我會爭辯說,它實際上*顯示了val和var *之間的區別:在val的情況下,如果您嘗試在'y = new A(「second()中使用'x'來代替'y',則會出現編譯錯誤「)',目前還不清楚爲什麼你聲明值類型與參考值之間的行爲沒有區別 –