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.
source share