views:

143

answers:

1

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

This works, at least in 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.

retronym
Thanks for answer. Do you know of an official source for the warnings about class inheritance?
Mitch Blevins
http://stackoverflow.com/questions/2058827/derived-scala-case-class-with-same-member-variables-as-base/2059203#2059203
retronym
Am I reading correctly that the deprecation is limited to case classes extending other case classes? My unexpected behavior above is a plain-jane class extending a case class.
Mitch Blevins
That's correct, the deprecation is limited to case classes (and objects) extending other case classes.
Seth Tisue