JamieP
JamieP

Reputation: 1774

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 finalinto the bytecode.

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

Upvotes: 5

Views: 555

Answers (1)

Victor Moroz
Victor Moroz

Reputation: 9225

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.

Upvotes: 9

Related Questions