Scala instance value area

Please note that this question and the like were asked earlier, for example, in Forward links - why is this code compiled? but I found answers that still remain some questions open, so I have another problem.

Inside the methods and functions, the effect of the keyword valseems lexical, i.e.

def foo {
  println(bar)
  val bar = 42
}

getting

error: forward reference extends over definition of value bar

However, in classes, visibility rules valseem to change:

object Foo {
  def foo = bar
  println(bar)
  val bar = 42
}

This compilation is not only compiled, but also printlnin the constructor will give 0as output, and a call fooafter the complete construction of the instance will lead to the expected value 42.

, , forward-reference, , , (, , ), , , , .

:

  • val ?

, - , , val , .

  • val, , ?

. .

  • ?

, val , val, , lazy.

  • val, , , ?

, , val lazy, val , , , , .

, - , val -alike, -, , , ?

+3
2

:

, - ...

.

  • ( )
  • , "foo".new ("bar")
  • ""

Ctors , , .

  • val, , ?

. , , - :

object Foo {
  def foo = bar
  println (bar.mkString)
  val bar = List(42)
}
// Exiting paste mode, now interpreting.

defined module Foo

scala> val foo=Foo 
java.lang.NullPointerException

val 2 , , null 0, , . - a - , - .

  • ?

, REPL . . , , () }. / , .

  • val, , , ?

Ctor, , Java, .

Java. , , :

public class FinalCheck
{
    final int foo;

    public FinalCheck ()
    {
        // does not compile: 
        // variable foo might not have been initialized
        // System.out.println (foo);

        // Does compile - 
        bar ();

        foo = 42;       
        System.out.println (foo);
    }

    public void bar () {
        System.out.println (foo);   
    }
    public static void main (String args[])
    {
        new FinalCheck ();
    }
}

... foo.

0
42

, , , , , - Java Scala.

+3

, , forward-reference , , , , (, , ), - , , .

- . . JVM ( , ), , .

  • val ?

    , - , , val val, .

, , .

  • val, , ?

    . .

. bar , , . , , .

: . , , , - ?

, ? .

  • ?

, val , , .

val , . , . :

class Foo {
  println(bar)
  val bar = 10
}

, , ? , REPL, , :

class Bar extends { override val bar = 42 } with Foo
new Bar

, bar . ​​

  • val, , ?

. , constuctor . :

println(bar)

, :

println(this.bar)

this, , , bar getter, .

, bar - , this bar getter.

+2

All Articles