4

为什么这无法编译(或工作?):

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

1 回答 1

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

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

于 2010-01-13T22:37:57.077 回答