3

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?

Owen
  • 448
  • 3
  • 11
  • 7
    `x` is immutable. That just means that `x` will always hold the same _instance_ of a `MyClass`. That instance might mutate but it will never be a different `MyClass` instance. – jwvh Apr 01 '19 at 06:35

1 Answers1

5

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?

Owen
  • 448
  • 3
  • 11
jgoday
  • 2,768
  • 1
  • 18
  • 17