Scala 对使用下划线的'Function2'参数的类型推断失败
为什么类型推断器放弃了这一点:Scala 对使用下划线的'Function2'参数的类型推断失败,scala,type-inference,Scala,Type Inference,为什么类型推断器放弃了这一点: def test(a: Seq[Int], b: Seq[Int]) = (a, b).zipped.map((_ + _) / 2) // no 像这样: <console>:35: error: missing parameter type for expanded function ((x$1, x$2) => x$1.$plus(x$2)) def test(a: Seq[Int], b:
def test(a: Seq[Int], b: Seq[Int]) = (a, b).zipped.map((_ + _) / 2) // no
像这样:
<console>:35: error: missing parameter type for expanded function
((x$1, x$2) => x$1.$plus(x$2))
def test(a: Seq[Int], b: Seq[Int]) = (a, b).zipped.map((_ + _) / 2)
^
如果为了好玩而添加另一对括号,它会再次失败:
def test(a: Seq[Int], b: Seq[Int]) = (a, b).zipped.map((_.+(_)) / 2) // no
我不记得它写在SLS的什么地方,但lambda desugares是最接近的范围
Map
需要一个函数(Int,Int)=>B
,因此当您编写Map(+()/2)
时,它被分解为所需的函数。但是在((++)/2)
或((++)()/2)
的情况下,你的lambda被分解成((x,y)=>x+y)/2)
,基本上你是在试图用2设计一个函数,这就是Scalac无法推断类型的原因
def test(a: Seq[Int], b: Seq[Int]) = (a, b).zipped.map((_.+(_)) / 2) // no