无法与案例对象匹配

时间:2015-02-25 11:07:10

标签: scala pattern-matching

尝试为链表实现一个超级简单的计数方法,但是当我尝试匹配我的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
                ^

我不明白的是,我总是与这样的案例对象相匹配,但现在它因某些原因无法运作......我该如何解决这个问题?

1 个答案:

答案 0 :(得分:8)

这是因为您匹配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
  }
}