使用下划线对 `Function2` 参数进行类型推断失败 [英] Type inference failing on a `Function2` argument using underscores
问题描述
为什么类型推断器会放弃这个:
Why does the type inferencer give up on this:
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)
^
这是一个奇怪的微妙之处,似乎与括号有关.例如,不使用中缀语法就可以工作:
This is a strange subtlety which seems to have to do with the parentheses. For example, without using infix syntax it works:
def test(a: Seq[Int], b: Seq[Int]) = (a, b).zipped.map(_.+(_) / 2) // yes
如果我为了好玩而添加另一对括号,它会再次失败:
If I add another pair of parentheses for the fun of it, it fails again:
def test(a: Seq[Int], b: Seq[Int]) = (a, b).zipped.map((_.+(_)) / 2) // no
推荐答案
我不记得它是在 SLS 中的哪个地方写的,但是 lambda 脱糖到最接近的范围.Map
需要一个函数 (Int, Int) =>B
,因此当您编写 map(_.+(_)/2)
时,它会被脱糖为预期的内容.但是在 ((_ + _)/2)
或 ((_.+(_))/2)
的情况下,您的 lambda 被脱糖为 (((x, y) => x + y)/2)
,基本上你是想设计一个 2 的函数,这就是为什么 Scalac 不能推断类型
I don't remember where in SLS it is written, but lambda desugares to the closest scope. Map
expects a function (Int, Int) => B
, so when you write map(_.+(_) / 2)
it is desugared into what is expected. But in the case of ((_ + _) / 2)
or ((_.+(_)) / 2)
your lambda is desugared into (((x, y) => x + y) / 2)
, basically you're trying to devise a function by 2 and that's why Scalac can't infer types
这篇关于使用下划线对 `Function2` 参数进行类型推断失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!