【发布时间】:2013-12-19 17:07:17
【问题描述】:
我的问题的上下文与论坛中其他人提出的问题相似,但我找不到完全匹配的内容,查看这些答案后我仍然是个谜。因此,如果有人可以提供帮助,我将不胜感激。我的问题的上下文是使用模式匹配来匹配单例类对象。
例如,如果我正在实现自己的列表结构,像这样
// An implementation of list
trait AList[+T] // covariant
case class Cons[+T](val head: T, val tail: AList[T]) extends AList[T]
case object Empty extends AList[Nothing] // singleton object
// an instance of implemented list
val xs = Cons(1, Cons(2, Cons(3, Empty)))
// pattern matching in a method - IT WORKS!
def foo[T](xs: AList[T]) = xs match {
case Empty => "empty"
case Cons(x, xss) => s"[$x...]"
}
println(foo(xs)) // => [1...]
// pattern matching outside - IT RAISES ERROR:
// pattern type is incompatible with expected type;
// found : Empty.type
// required: Cons[Nothing]
val r: String = xs match {
case Empty => "EMPTY"
case Cons(x, xss) => s"[$x...]"
}
println(r) // does NOT compile
在我看来,它们在相同的“对象”上看起来是相同的“匹配”,为什么一个有效而另一个失败?我猜这个错误与匹配 expr in 和 out 方法的不同有关,但是编译器给出的消息非常具有误导性。这是否意味着我们需要在外部“匹配”时像 xs.asInstanceOf[AList[Int]] 一样显式转换 xs?
【问题讨论】:
标签: scala singleton pattern-matching