这是从 coursera 函数式编程类(class)交叉发布的,因为该论坛上的事件要少得多。
我编写了以下代码(部分内容被编辑,因为它是家庭作业):
type Occurrences = List[(Char, Int)]
def subtract(x: Occurrences, y: Occurrences): Occurrences = {
val mx: Map[Char, Int] = x toMap
y.foldLeft (redacted) (redacted => simple expression using updated and -)) toList
}
这会产生以下编译错误:
type mismatch; found : Map[Char,Int] required: <:<[(Char, Int), (?, ?)]
但是,如果我通过 val 语句在中间添加第三行的副本(没有 toList),错误就会消失:
type Occurrences = List[(Char, Int)]
def subtract(x: Occurrences, y: Occurrences): Occurrences = {
val mx: Map[Char, Int] = x toMap
val foo: Map[Char, Int] = y.foldLeft (redacted) (redacted => simple expression using updated and -))
y.foldLeft (redacted) (redacted => simple expression using updated and -)) toList
}
我猜这与向类型检查器提供某种额外提示有关,但是有人知 Prop 体为什么会发生这种情况吗?
最佳答案
下面是一些示例以及关于为什么会发生这种情况的一些解释。
首先,工作和非工作情况:
scala> { List('a -> 1, 'b -> 2).toMap
| println("aaa") }
aaa
scala> { List('a -> 1, 'b -> 2) toMap
| println("aaa") }
<console>:9: error: type mismatch;
found : Unit
required: <:<[(Symbol, Int),(?, ?)]
println("aaa") }
^
发生这种情况是因为语法“obj method arg”被认为是“obj.method(arg)”,“obj method\n arg”也是如此,这样参数就可以写在下一行中。通知如下:
scala> { val x = List('a -> 1, 'b -> 2) map
| identity
|
| println(x) }
List(('a,1), ('b,2))
与 List('a -> 1, 'b -> 2).map(identity)
相同.
现在出现奇怪的错误消息 found : Unit, required: <:<[(Symbol, Int),(?, ?)]
。碰巧toMap
实际上需要一个参数,这是它的签名:
def toMap[T, U](implicit ev: <:<[A,(T, U)]): Map[T,U]
,
但它是一个隐式参数,因此在这种情况下不需要显式提供。但是当您使用obj method \n arg
时它填充方法参数的语法。在上面的非工作示例中,参数是 println
其类型为 Unit
,因此编译器不接受它。
一种解决方法是有两个 \n
分隔线:
scala> { List('a -> 1, 'b -> 2) toMap
|
| println("aaa") }
aaa
您还可以使用;
分隔线。
关于scala - 在 scala 中,在 toMap 之后添加不相关的行时编译错误消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13113327/