How is the shaft unchanged?

I know that valnot finalunless explicitly declared, and using javap confirms that Scalac is not pasting into finalbytecode.

So, is it valimmutable simply because the compiler does not allow us to write any code that tries to change it?

+4
source share
1 answer

final and immutability are two orthogonal concepts:

val means that you cannot change (mutate) a variable by assigning it anything after the initial declaration:

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

In the JVM bytecode, it is implemented by creating a private member and 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; }
  ...
}

finalmeans you cannot override valin 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 , var val.

+8

Source: https://habr.com/ru/post/1656598/


All Articles