Reputation: 597026
def toJson[T](obj: T) = {
gson.toJson(obj)
}
def toJson[T](list: Seq[T]) = {
toJson(seqAsJavaList(list))
}
This doesn't compile. And that's documented as a feature (see this answer):
When a method is overloaded and one of the methods calls another. The calling method needs a return type annotation.
The question is: why?
From the above link + some additional thought from colleagues, here are the possible reasons:
I know it's a best practice to specify the return type anyone, but why actually is the above snippet not compiling, and if return type inference isn't good enough, why is it there in the first place?
Upvotes: 3
Views: 188
Reputation: 9705
Might not be the main reason, but note that another reason for an explicit parameter is given as:
When a method is recursive.
The problem is, depending on the return type of the "calling" function, the call can either be to its namesake, or to itself (i.e. recursive).
Let's say:
trait C
class A extends C
def a(obj: A) = {2}
Now consider:
def a[T <: C](obj: T): Int = {
a(obj)
}
a(new A) //an Int, 2
versus:
def a[T <: C](obj: T): Any = {
a(obj)
}
a(new A) //infinite recursion
Since inferring the return type of a recursive function is finite-time undecidable in general, inferring the return type of the "calling" function is also finite-time undecidable in general.
Upvotes: 1