2010-01-13 92 views
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?") 
    } 
+1

我认为这是目前在模式匹配上开放的漏洞之一。 – 2010-01-13 23:27:14

回答

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 

我还没有找到一个指向特定导致原始问题的错误,但忽略关于在您自己的危险中关于案例类继承的警告。

+0

感谢您的回答。你知道关于类继承警告的官方消息吗? – 2010-01-13 23:02:57

+0

http://stackoverflow.com/questions/2058827/derived-scala-case-class-with-same-member-variables-as-base/2059203#2059203 – retronym 2010-01-14 12:49:13

+0

我是否正确阅读,反对仅限于案例类扩展其他案例类?我上面出乎意料的行为是一个简单的类扩展案例类。 – 2010-01-14 17:56:48