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?

1
  • 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. Commented Apr 1, 2019 at 6:35

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.