Since and I quote from Martin Odersky:
In this case:
def loop: Boolean = loopval x = loop // Leads to an infinite loopIn this case:
val y: Boolean = y // Evaluated to falseI'm a little confused why:
val x = loop // doesn't get evaluated to false?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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With