Justification of behavior overriding the value of val

class A { val x = println("A") } class B extends A { override val x = println("B") } (new B).x 

Print

 A B 

However

 class A { lazy val x = println("A") } class B extends A { override lazy val x = println("B") } (new B).x 

Print only:

 B 

According to Martin Odersky , behavior, at least in a non-case, is โ€œindicatedโ€. I am curious why the behavior is set this way and why it is different when val is lazy.

+6
source share
2 answers

The code in the template ("body") of the class definition, outside the member definitions, is what is included in the constructor. Constructors of parent classes are always called when initializing an instance of a child class (in this case, you call the constructor without arguments, otherwise the syntax will be class B extends A(arg1, arg2) { ... } ). For more information, see Section 5.1 in the Scala Language Specification .

This is why println("A") is evaluated in the first case; that val definition is part of the constructor code.

When you think about what happens during construction in the second example, you never asked for the value of x defined in A ; now, since it is lazy val , it will not be calculated before it is needed.

You can think of lazy val as methods that take no arguments and cache their output on the first call. You did not name this method here, you just defined it.

+12
source
 class A { val x = println("A") } class B extends A { override val x = println("B") } (new B).x 

At runtime, all initializations of val (and other statements) are executed. Therefore, val x = println("A") is executed as part of construct A and override val x = println("B") is executed as part of construct B They both print some line and initialize x to () (of type Unit ), so redefinition is just a red herring. .x (from (new B).x ) does nothing.

In the lazy case, you initialize x with something like a function with no arguments and return Unit . It does not start until you read .x , and since x overridden, only "B" is printed in this case.

+1
source

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


All Articles