假设此类型的推理代码用于列表中的推理元素,
def doStuff[A](x: List[A]) = x // ignore the result
doStuff(List(3)) // I dont need to speicify the type Int here
但是,如果类型A与其他类型一起使用,则类型推断不起作用,我必须指定类型。
def doStuff[A, B](x: List[A], f: (B, A) => B) = {
}
doStuff(List(3), (x: String, y) => x) //compilation failed, missing parameter type
doStuff[Int, String](List(3), (x, y) => x) //compilation fine.
我可以知道为什么吗?
提前谢谢了
类型推断仅适用于单独的参数列表。如果更改doStuff
为以下内容:
def doStuff[A, B](x: List[A])(f: (B, A) => B) = {
}
类型推断将按您期望的那样工作:
doStuff(List(3))((x: String, y) => x)
但是,请注意,类型推断是从左到右的,因此,如果将其Nil
作为第一个参数,它将进行推断A = Nothing
,而这几乎永远不是您想要的。
更新
在您的原始示例中,调用doStuff(List(3), (x: String, y) => x)
失败,因为y
无法推断lambda的类型。的List(3)
是相同的参数列表,因此A
尚不清楚。因此,没有提示的类型,y
并且编译器将失败。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句