简体   繁体   中英

Mutable fields of immutable values in Scala

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 xm mutable or immutable?

xm 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 val ue x owns an immutable pointer to the variable xm (ie. you cannot change the container xm 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM