Why does Scala fail to infer the return type of the method when there’s an explicit return statement used in the method?
For instance, why does the following code compile?
object Main {
def who = 5
def main(args: Array[String]) = println(who)
}
But the following doesn’t.
object Main {
def who = return 5
def main(args: Array[String]) = println(who)
}
The return type of a method is either the type of the last statement in the block that defines it, or the type of the expression that defines it, in the absence of a block.
When you use
returninside a method, you introduce another statement from which the method may return. That means Scala can’t determine the type of thatreturnat the point it is found. Instead, it must proceed until the end of the method, then combine all exit points to infer their types, and then go back to each of these exit points and assign their types.To do so would increase the complexity of the compiler and slow it down, for the sole gain of not having to specify return type when using
return. In the present system, on the other hand, inferring return type comes for free from the limited type inference Scala already uses.So, in the end, in the balance between compiler complexity and the gains to be had, the latter was deemed to be not worth the former.