Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is a val immutable?

Tags:

scala

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?

like image 244
JamieP Avatar asked Feb 06 '23 00:02

JamieP


1 Answers

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.

like image 56
Victor Moroz Avatar answered Feb 16 '23 13:02

Victor Moroz