“Missing parameter type” in overloaded generic method taking a function argument

此生再无相见时 提交于 2019-12-10 04:08:10

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6448444/missing-parameter-type-in-overloaded-generic-method-taking-a-function-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!