[英]“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: 我在我的DSL中遇到问题,重载泛型方法导致编译器希望我添加显式参数类型:
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: 为了证明重载不是scalac本身的歧义问题,这里是一个没有类型参数的版本,它可以很好地工作:
def beta(fun: Int => String): String = fun(66).reverse
def beta(thunk: => String): String = thunk.reverse
beta(_.toString) // ok
beta("gaga") // ok
The problem is that Int => T
is also a type. 问题是Int => T
也是一种类型。 For example, say you defined just the second beta
: 例如,假设您仅定义了第二个beta
:
def beta[ T ]( thunk: => T ) : String = thunk.toString
And now you pass a function Int => Int
to it: 现在你将函数Int => Int
传递给它:
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? 所以,假设函数适合=> T
,并且你还有一个Int => T
,那么Scala应该知道你想要哪一个? It could be a String
, for instance: 它可以是一个String
,例如:
scala> beta((_: String) + 11)
res1: String = <function1>
How could Scala assume it was an Int
? Scala怎么会认为它是一个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. 您可能已经意识到,问题出现是因为您的beta函数已经过载。 When you define: 当你定义:
beta { _ + 22 }
which beta do you expect it do call? 你期望它打电话给哪个beta? 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. Scala不能知道_
是Int
是因为你用22求和它。所以对于这个特例,你必须定义_
是什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.