Possible Duplicate:
Scala and forward references
Is there any rationale why the following works in Scala:
Version 1
object Strange extends App {
val x = 42
Console.println(x) // => outputs "42", as expected
}
Version 2
object Strange extends App {
Console.println(x) // => "0" ?!
val x = 42
}
Why does it compile at all and why behaves so weird without any warnings or whatsoever?
It's also the same issue with class
:
class StrangeClass {
Console.println(x) // => still "0"
val x = 42
}
object TestApp extends App {
new StrangeClass()
}
There are no such issue with regular method's body:
def nonStrangeMethod {
Console.println(y) // => fails with "not found: value y", as expected
y = 42
}
And behavior changes dramatically if we'd add "final" to val declaration:
class StrangeClass {
Console.println(x) // => "42", but at least that's expected
final val x = 42
}
For records, the following Java static (Scala's object
) counterpart:
public class Strange {
static {
System.out.println(x);
}
static int x = 42;
public static void main(String[] args) {}
}
fails compilation with plain & understandable error "Cannot reference a field before it is defined" on line #3 and Java non-static (Scala's class
) counterpart:
public class Strange {
Strange() {
System.out.println(x);
int x = 42;
}
public static void main(String[] args) {
new Strange();
}
}
obviously fails with "x cannot be resolved to a variable" on line #3.