JamieP JamieP - 21 days ago 4x
Scala Question

How is a val immutable?

I know that a

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

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


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.