在Scala中匹配案例类的子类

时间:2010-01-13 22:22:09

标签: scala pattern-matching case-class

为什么这不能编译(或工作?):

  case class A(x: Int)
  class B extends A(5)

  (new B) match {
    case A(_) => println("found A")
    case _ => println("something else happened?")
  }

编译错误是:

constructor cannot be instantiated to expected type;  found   : blevins.example.App.A  required: blevins.example.App.B

请注意,这会按预期编译并运行:

  (new B) match {
    case a: A => println("found A")
    case _ => println("something else happened?")
  }

附录

仅供参考,编译并运行良好:

  class A(val x: Int)
  object A {
    def unapply(a: A) = Some(a.x)
  }
  class B extends A(5)

  (new B) match {
    case A(i) => println("found A")
    case _ => println("something else happened?")
  }

1 个答案:

答案 0 :(得分:4)

这很有效,至少在2.8:

scala>   case class A(x: Int)                           
defined class A

scala>   class B extends A(5)                           
defined class B

scala>   (new B: A) match {                             
     |     case A(_) => println("found A")              
     |     case _ => println("something else happened?")
     |   }                                              
found A

我没有找到指向导致原始问题的特定错误的指针,但忽略了有关自己风险的案例类继承的警告。