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
.