无法与案例对象匹配

can't match against case object

尝试为链表实现一个超级简单的计数方法,但是当我尝试匹配我的 case 对象的模式时出现错误。

代码如下:

trait LinkedList[+A] {
  def count = 0
}

case object Leaf extends LinkedList[Nothing]

case class  Node[A](head: A, tail: LinkedList[A]) extends LinkedList[A] {
  override def count: Int = this match {
    case Node(_, t) => 1 + t.count
    case Leaf => 0
  }
}

这是错误:

scala> :load LinkedList.scala
Loading LinkedList.scala...
defined trait LinkedList
defined module Leaf
<console>:17: error: pattern type is incompatible with expected type;
 found   : Leaf.type
 required: Node[A]
Note: if you intended to match against the class, try `case _: <none>`
           case Leaf => 0
                ^

我不明白的是,我总是像这样匹配 case 对象,但现在由于某种原因它不起作用...我该如何解决这个问题?

因为你匹配的是this,是一个NodeLeaf 不是 Node,因此 this 永远不可能是 Leaf。编译器基本上是在告诉您 Leaf 情况永远不会发生,因此您可能有一个错误。

要修复错误,请删除该案例。无论如何你都不需要它,因为叶子案例是由特征上定义的默认 count 方法处理的。这意味着该方法应该简化为更直观的:

override def count: Int = 1 + tail.count

或者将 count 方法移动到特征:

trait LinkedList[+A] {
  def count: Int = this match {
    case Node(_, t) => 1 + t.count
    case Leaf => 0
  }
}