Scala:我如何只匹配任意List的前两个元素

时间:2014-08-06 17:15:55

标签: list scala generics pattern-matching match

我试图匹配列表前两个元素,但是,它不会接受任意长度的列表。以下代码失败。

  def demoCases() = {
    def actor1 = new Actor[Employee] {}
    def actor2 = new Actor[Employee] {}
    def actor3 = new Actor[Animal] {}

    var actors = List(actor1, actor2, actor3);
    println();
    actors match {
      case (_: Employee) :: (_: Employee) :: tail
        => {println("nice 2  employees to start with ")};

      case Nil
        => {println("no match")}
    }

例外:

Exception in thread "main" scala.MatchError: List(.....)

如何指定列表中只有 first 的两个元素需要匹配此表达式?

2 个答案:

答案 0 :(得分:1)

只需将case Nil替换为case _ => println("no match")_作为模式意味着"匹配任何内容"。但请注意,您的第一个案例要求列表的前两个元素为Employee s,而不是Actor s。

答案 1 :(得分:1)

由于类型擦除(Alexey Romanov指出),以下内容无法正常工作

case (_: Actor[Employee]) :: (_: Actor[Employee]) :: tail

因此,如果不重组代码,我无法想办法做任何你想要的事情。例如,如果您以某种方式将Employee作为Actor的成员,并使Actor成为案例类,则可以执行

case Actor(_: Employee) :: Actor(_: Employee) :: tail