2010-01-13 126 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