"Missing parameter type" in an overloaded generic method using function argument

I have a problem in my DSL with overloaded generic methods, as a result of which the compiler wants 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. 

Is there any chance that I can get rid of the mess on the last line?

EDIT:

To demonstrate that overloading is not an ambiguity problem for a scalar per se, here is a version without a type parameter that works fine:

 def beta(fun: Int => String): String = fun(66).reverse def beta(thunk: => String): String = thunk.reverse beta(_.toString) // ok beta("gaga") // ok 
+7
source share
2 answers

The problem is that Int => T also a type. For example, let's say you only defined the second beta :

 def beta[ T ]( thunk: => T ) : String = thunk.toString 

And now you pass it the function Int => Int :

 scala> beta((_: Int) + 1) res0: String = <function1> 

So, given that the function is suitable for => T , and that you also have Int => T , how should Scala know which one you want? It could be a String , for example:

 scala> beta((_: String) + 11) res1: String = <function1> 

How does Scala assume that it was Int ? The examples you showed to demonstrate overloading are not to blame, they don’t show anything like that, because you got rid of the type parameters in them.

+4
source

As you may have understood, the problem is due to overloading the beta function. When you define:

 beta { _ + 22 } 

What beta version do you expect from the call? Scala cannot know that _ is Int just because you sum it up with 22. So, for this specific example, you need to determine what _ .

+1
source

All Articles