If you use
val y: Boolean = y
in statement position inside method body, it doesn't evaluate to anything at all, because it gives a compile time error:
error: forward reference extends over definition of value y
However, if you use it as a member variable, it compiles to a separate private variable initialized with _, a getter def, and a separate initializer:
private[this] val y: Boolean = _;
<stable> <accessor> def y(): Boolean = XeqX.this.y;
[...]
def <init>(): WhateverYourClassIsCalled.type = {
XeqX.super.<init>();
XeqX.this.y = XeqX.this.y();
()
}
Since _ on right hand side for booleans evaluates to default value false, by the time you access it in initializer, the member y is already set to false.
In contrast to that
def loop: Boolean = loop
never terminates once it's called. Therefore
val x = loop
tries to evaluate its right hand side immediately, and then hangs forever.
Here is another answer for a similar problem (again, difference between def and val).
loopyou need first to evaluate the value ofloop. It's a recursive call without escape condition - SimY4val x = loopshould just hang forever. What's not so obvious is whyval y: Boolean = ydoes anything at all. - Andrey Tyukin