case class Test(kind: Int) {
val ifX = if (isX) "is X" else "not X"
val isX = kind == 1
}
val test = Test(1)
println("ifX=%s, isX=%b".format(test.ifX, test.isX))
Why this code print:
ifX=not X, isX=true
When is move “val ifX” before “ifX” it’s ok (print ifX=is X)
EDIT: I know how to fix that. I can’t understand why compiler not issue warning or error in this situation.
You are making the assumption that order doesn’t matter in scala. It does. Because isX is a
variablevalue, and while it’s defined when ifX runs, it’s value is still uninitialized, and so it is the default for its type (boolean, so false).If you redefine isX as a function (
def isX = ...) it would work.This is roughly equivalent to the following Java: