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

烂漫一生 提交于 2019-12-05 04:26:02

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.

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