“缺少参数类型”在重载泛型方法中使用函数参数 [英] "Missing parameter type" in overloaded generic method taking a function argument

查看:142
本文介绍了“缺少参数类型”在重载泛型方法中使用函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  

我的DSL在重载泛型方法时遇到问题,导致编译器想要添加显式参数类型。 (fun:Int => T):String = fun(33).toString

def beta [T] (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} //好的...哎哟。

任何机会我都可以摆脱最后一行的混乱状态?



编辑:
$ b

为了证明重载本身并不是一个模糊问题,这里是一个没有类型参数的版本可以很好地工作:

  def beta(fun:Int => String):String = fun 66)。反向
def beta(thunk:=> String):String = thunk.reverse

beta(_。toString)// ok
beta(gaga )// ok


解决方案

问题在于 Int => T 也是一种类型。例如,假设您定义了第二个 beta

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

现在你通过函数 Int => Int 它:

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

因此,假设函数符合 => T ,而且 也有 Int => T ,斯卡拉应该怎么知道你想要哪一个?它可以是 String ,例如:

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

Scala如何假定它是 Int ?你已经证明过载的例子不是怪罪,因为你已经摆脱了它们的类型参数。

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

解决方案

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.

这篇关于“缺少参数类型”在重载泛型方法中使用函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆