简体   繁体   English

在Scala中匹配案例类的子类

[英]Matching sub-classes of case classes in Scala

Why does this fail to compile (or work?): 为什么这不能编译(或工作?):

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

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

The compiler error is: 编译器错误是:

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

Note that this compiles and runs as expected: 请注意,这将按预期编译并运行:

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

ADDENDUM 附录

Just for reference, this compiles and runs fine: 仅供参考,这编译并运行良好:

  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?")
  }

This works, at least in 2.8: 这有效,至少在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

I haven't found the a pointer to the particular bug that causes the original problem, but ignore the warnings about case class inheritance at your own peril. 我没有找到导致原始问题的特定错误的指针,但忽略了关于案例类继承的警告,这是你自己的危险。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM