The Scala compiler currently cannot infer return types of recursive methods as in the following code
def foo(i:Int) = if (i > 0) foo (i-1) else 0
Is there any ambuigity in the above statement? (i.e., is any type other than Int possible?)
I can imagine that in more complex example, it will be difficult to infer the type.
Is it possible to further characterize the cases of recursive methods where we can(not) infer the types?
[EDIT:] The compiler is intelligent enough to figure out that String is incorrect.
scala> def foo(i:Int):String = if (i > 0) foo (i-1) else 0
<console>:5: error: type mismatch;
found : Int(0)
required: String
If your recursive call is always in the last position, i.e. its value is never used and only returned, it should be possible to determine the type as the common supertype of all other branches.
However, in a situation like
you would not know the type of
foo(i - 1) + 1(or understand the operation+because it is actually a method onfoo– things are getting more complicated in the presence of objects) without knowing whatfoois. So, again you’re moving around in circles.