JamieP JamieP - 2 months ago 6
Scala Question

How is a val immutable?

I know that a

val
is not
final
unless explicitly declared so and using javap confirms that Scalac is not inserting
final
into the bytecode.

So is a
val
immutable simply because the compiler stops us from writing any code that attempts to mutate it?

Answer

final and immutability are two orthogonal concepts:

val means you can't change (mutate) a variable by assigning anything to it after initial declaration:

val x = 1
x = 2 // error: reassignment to val

In JVM bytecode it's implemented by creating a private member and a getter, but not setter:

class A {
  val x = 1
}

=>

// Java equivalent of a generated bytecode
public class A {
  private final int x;
  public int x() { return x; }
  ...
}

final means you can't override your val in a subclass:

class A {
  final val x = 1
}

class B extends A { 
  override val x = 2
}

// error: overriding value x in class A of type Int(1);
//  value x cannot override final member

final will cause the same error if you use var instead of val.