"Missing parameter type" in overloaded generic method taking a function argument
I am having a problem in my DSL with overloaded generic methods resulting in the compiler wanting me to add explicit parameter types:
def alpha[T](fun: Int => T): String = fun(33).toString
def beta [T](fun: Int => T): String = fun(66).toString
def beta [T](thunk: => T): String = thunk.toString
alpha { _ + 11 } // ok
beta { _ + 22 } // "error: missing parameter type for expanded function"
beta { _: Int => _ + 22 } // ok... ouch.
Any chance I can get rid of the the clutter in the last line?
EDIT:
To demonstrate that the overloading is not an ambiguity problem to scalac per se, here is a version without type parameter which works perfectly fine:
def beta(fun: Int => String): String = fun(66).reverse
def beta(thunk: => String): String = thunk.reverse
beta(_.toString) // ok
beta("gaga") // o开发者_如何学Pythonk
The problem is that Int => T
is also a type. For example, say you defined just the second beta
:
def beta[ T ]( thunk: => T ) : String = thunk.toString
And now you pass a function Int => Int
to it:
scala> beta((_: Int) + 1)
res0: String = <function1>
So, given that a function fits => T
, and that you also have an Int => T
, how is Scala supposed to know which one you want? It could be a String
, for instance:
scala> beta((_: String) + 11)
res1: String = <function1>
How could Scala assume it was an Int
? The examples you have shown to demonstrate overload isn't to blame don't demonstrate any such thing, because you got rid of the type parameters in them.
As you might have realized, the issue occurs because you have beta function is overloaded. When you define:
beta { _ + 22 }
which beta do you expect it do call? Scala cannot know that _
is an Int
just because you are summing it with 22. So for this particular example, you have to define what _
is.
精彩评论