Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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")      // ok
like image 585
0__ Avatar asked Jun 23 '11 01:06

0__


2 Answers

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.

like image 116
Daniel C. Sobral Avatar answered Oct 05 '22 02:10

Daniel C. Sobral


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.

like image 42
rafalotufo Avatar answered Oct 05 '22 02:10

rafalotufo