【问题标题】:Type inference failing on a `Function2` argument using underscores使用下划线对“Function2”参数进行类型推断失败
【发布时间】:2013-11-29 11:05:57
【问题描述】:

为什么类型推断器放弃了这个:

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)   // yes

如果我为了好玩而添加另一对括号,它会再次失败:

def test(a: Seq[Int], b: Seq[Int]) = (a, b).zipped.map((_.+(_)) / 2)   // no

【问题讨论】:

    标签: scala type-inference


    【解决方案1】:

    我不记得它在 SLS 中的哪个位置,但 lambda 脱糖到最接近的范围。 Map 需要一个函数 (Int, Int) =&gt; B,因此当您编写 map(_.+(_) / 2) 时,它会被取消为预期的内容。但是在((_ + _) / 2)((_.+(_)) / 2) 的情况下,你的 lambda 被脱糖为(((x, y) =&gt; x + y) / 2),基本上你试图设计一个 2 的函数,这就是为什么 Scalac 不能推断类型

    【讨论】:

      猜你喜欢
      • 2018-12-13
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      • 2017-11-05
      • 1970-01-01
      • 2018-08-21
      • 1970-01-01
      • 2020-12-30
      相关资源
      最近更新 更多