Scala - How guaranteed the immutability of val at run time

When we create a final in java, it is guaranteed that it cannot be changed even at run time, because the JVM guarantees it.

Java class:

public class JustATest {
    public final int x = 10;
}

Javap is decompiled:

Compiled from "JustATest.java"

public class JustATest {
  public final int x;

  public JustATest();
    Code:
       0: aload_0
       1: invokespecial #1                // Method java/lang/Object."<init>":()V
       4: aload_0
       5: bipush        10
       7: putfield      #2                  // Field x:I
      10: return
}

But in scala, if we declare val, it compiles to a normal integer and there is no difference between var and val in terms of decompilation output.

Original Scala class:

class AnTest {

  val x = 1
  var y = 2
}

Decompiled output:

Compiled from "AnTest.scala"
public class AnTest {
  public int x();
    Code:
       0: aload_0
       1: getfield      #14                 // Field x:I
       4: ireturn

  public int y();
    Code:
       0: aload_0
       1: getfield      #18                 // Field y:I
       4: ireturn

  public void y_$eq(int);
    Code:
       0: aload_0
       1: iload_1
       2: putfield      #18                 // Field y:I
       5: return

  public AnTest();
    Code:
       0: aload_0
       1: invokespecial #25                 // Method java/lang/Object."<init>":()V
       4: aload_0
       5: iconst_1
       6: putfield      #14                 // Field x:I
       9: aload_0
      10: iconst_2
      11: putfield      #18                 // Field y:I
      14: return
}

With this information, the concept of the immutability of a valis only controlled at compile time by the Scala compiler? How is this guaranteed at runtime?

+4
source share
2 answers

Scala val - , . Java , final, , Scala val , , . , final, , Java:

class AnTest {
  final val x = 10
}

:

public class testing.ReadingFile$AnTest$1 {
  private final int x;

  public final int x();
    Code:
       0: bipush        10
       2: ireturn

  public testing.ReadingFile$AnTest$1();
    Code:
       0: aload_0
       1: invokespecial #19                 // Method java/lang/Object."<init>":()V
       4: return
}

, Java, , x.

+11

: Scala, - JVM, .

, , - JVM, . sealed private[this], val. , - JVM Scala, , Scala, , Scala.

JVM, Scala.js, (ECMAScript) , - JVM.

, : , Haskell, , , . , Haskell () , , .

+1

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


All Articles