Type inference on method return type

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 return inside a method, you introduce another statement from which the method may return. That means Scala can’t determine the type of that return at 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.

Leave a Comment