Scala internals var and val

What is the internal implementation of var and val in Scala? They are interested in knowing the details of their implementations - what var a "var" does, how the variable structure vs val (more final) is implemented, which makes it unchanged.

+4
source share
2 answers

I will answer with an example using scalacand javap.

First I create Test.scala:

class Test {
  val x = 1
  var y = 2
}

Compile it with using scalac Test.scalato generate Test.class, then use javap -p Test.classto get

public class Test {
  private final int x;
  private int y;
  public int x();
  public int y();
  public void y_$eq(int);
  public Test();
}

So, you can see that it has val xbecome a field private finalin the class, as well as a method public finalto return this value.

var y getter + setter. y_$eq(int) - . scala def y_=(newY: Int): Unit. Scala y = someValue y_=(someValue).

+12

( ) ( , , )

A var decl 4.2 /.

a val .

: .

, :

scala> class X { final val x = 7 }  // the underlying field is not initialized
defined class X

scala> :javap -prv X
{
[snip]
  private final int x;
    flags: ACC_PRIVATE, ACC_FINAL
[snip]
  public $line5.$read$$iw$$iw$X();
    flags: ACC_PUBLIC
    Code:
      stack=1, locals=1, args_size=1
         0: aload_0       
         1: invokespecial #14                 // Method java/lang/Object."<init>":()V
         4: return        

:

scala> class Y { def y = { var z = 0; def z_=(zz: Int): Unit = ???; z = 1; z } }

scala> class Y { var z = 0; def z_=(zz: Int): Unit = ???; z = 1 }
<console>:7: error: method z_= is defined twice

REPL ( ):

scala> var z = 0 ; def z_=(zz: Int): Unit = ???
<console>:7: error: method z_= is defined twice
  conflicting symbols both originated in file '<console>'
       var z = 0 ; def z_=(zz: Int): Unit = ???
                       ^

scala> { var z = 0 ; def z_=(zz: Int): Unit = ??? }
+4

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


All Articles