在我的代码中,我有以下内容:
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
?
最佳答案
发生错误是因为您编写了 xs foldLeft (init) (f)
而不是 (xs foldLeft init)(f)
或 xs.foldLeft(init )(f)
.
前者不起作用,因为 Scalas 运算符符号规则只允许在 obj 方法参数
形式中发生调用时留下点和括号,而 foldLeft< 则不是这种情况
因为它有两个参数列表。
关于Scala - foldLeft 类型推断失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13108527/