Scala's wrong forward reference error
Well, don't I feel stupid now...
private def foo(a:A):B = a match{
case A(...) =>
val x = a.b //error: wrong forward reference a
...
val a = ... //<-- THAT's the reason for the error
...
}
So a simple rename will resolve the issue:
private def foo(aa:A):B = aa match{
case A(...) =>
val x = aa.b
...
val a = ...
...
}
Here is an attempt to explain what @User1291 had not with his/her answer.
I'm new to Scala and Java so the answer wasn't obvious to me. I was surprised to run into this error in my (simplified) code:
object Main {
val data = getData()
def getUser() = {
getUserFrom(data) // error: Wrong Forward Reference
}
}
Wrong Forward Reference is equivalent to Java's Illegal Forward Reference, which is a fancy way of saying you can't reference a value that isn't known at compile time. In this case, getData()
can only return value during run time, and referencing data
gave this error.
When I tried changing the code to reference a known string, as expected the error went away:
object Main {
val name = "PieOhPah"
def getUser() = {
getUserFrom(name)
}
}
Another way is to close over the value with a function and access it from inside since functions are not evaluated until runtime:
object Main {
val data = getData()
def getUser(userData: UserData) = {
getUserFrom(userData)
}
// Invoke the method later with `data`
print(getUser(data).name)
}