Reputation: 466
Consider a simple class and a (immutable) value instance of it:
class MyClass (var m: Int) {}
val x : MyClass = new MyClass(3)
Since m
is declared as a variable (var
), m
is mutable. However, since x
is declared as a value, it is immutable. Then is x.m
mutable or immutable?
Upvotes: 3
Views: 473
Reputation: 2836
x.m
is mutable.
The following code is valid:
class MyClass (var m: Int) {}
val x : MyClass = new MyClass(3)
println(x.m)
x.m = 7
println(x.m)
val holds a variable that cannot be changed, but in this case it does not make it constant. Indeed, it can have mutable internal fields (as in this case through var). Conceptually, the value x
owns an immutable pointer to the variable x.m
(ie. you cannot change the container x.m
refers to) but the integer itself (ie. the container contents) is mutable.
Related: What is the difference between a var and val definition in Scala?
Upvotes: 5