Scala - foldLeft类型推断失败

3

在我的代码中,我有以下内容:

  type Occurrences = List[(Char, Int)]

  def subtract(x: Occurrences, y: Occurrences): Occurrences = {
    val yMap = y.toMap
    x foldLeft (List[(Char, Int)]()) {  // ERROR
        case (a: List[(Char, Int)], xe: (Char, Int)) =>
        if(yMap.contains(xe._1)) (xe._1 -> (xe._2 - yMap(xe._1))) :: a
        else a
    }
  }

它在编译时失败,就在代码中错误标记之前的{处。错误信息如下:

missing parameter type for expanded function The argument types of an anonymous function must be fully known. (SLS 8.5) Expected type was: Int

1) 这怎么可能呢?据我所见,这里没有类型信息的曲解空间,而且我在互联网上发现了很多这样的例子。我该怎么修复它?
2) 它为什么最终认为期望的类型是Int

为什么在foldLeft中漏掉点号会导致编译错误? - Régis Jean-Gilles
1个回答

8
错误是因为您写成了 xs foldLeft (init) (f) 而不是 (xs foldLeft init)(f) 或者 xs.foldLeft(init)(f)
前者无法正常工作,因为Scala的操作符符号规则只允许在调用形式obj method param 中保留点和括号,而这并不适用于foldLeft ,因为它有两个参数列表。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接