我有一個簡單的類層次結構代表了幾個不同類型頂點的使用情況下,類實現的圖形狀結構:更換的情況下類的繼承與提取保存全面性檢查斯卡拉
sealed trait Node
sealed abstract case class Vertex extends Node
case class Arc extends Node
case class VertexType1 (val a:Int) extends Vertex
case class VertexType2 (val b:Int) extends Vertex
這讓我寫匹配塊是這樣的:
def test (x: Node) = x match {
case _ : Arc => "got arc"
case _ : Vertex => "got vertex"
}
或這樣的:
def test (x: Node) = x match {
case _ : Arc => "got arc"
case c : Vertex => c match {
case _ : VertexType1(a) => "got type 1 vertex " + a
case _ : VertexType2(a) => "got type 2 vertex " + a
}
}
請注意,此實現具有以下屬性:
1)它允許編寫區分弧和頂點但不在特定頂點類型之間的匹配塊,還可以匹配區分頂點類型的塊。
2)在這兩個頂點類型特異性和非頂點類型專用匹配塊模式匹配的窮盡被檢查。
但是,不推薦使用case類的繼承,編譯器建議使用提取器來支持非葉節點上的匹配(即,在上例中,爲了區分弧和頂點,而不是在頂點類型之間) 。
的問題:是有可能實現類似的類層次結構,而無需使用情況下類的繼承,但仍具有圖案全面性如上所示通過在這兩種情況下,使用編譯器執行檢查?
編輯:我已經向VertexType類添加了一個構造函數參數,以便匹配不僅僅在類型上執行。
我沒有case類目前實現如下:
sealed trait Node
sealed abstract class Vertex extends Node
class Arc extends Node
class VertexType1 (val a:Int) extends Vertex
class VertexType2 (val b:Int) extends Vertex
object VertexType1 {
def unapply (x : VertexType1) : Some[Int] = Some(x.a)
}
object VertexType2 {
def unapply (x : VertexType2) : Some[Int] = Some(x.b)
}
並測試代碼:
def test (x: Node) = x match {
case _ : Arc => "got arc"
case v : Vertex => v match {
case VertexType1(a) => "got vertex type 1 " + a
}
}
我期待有一個關於非詳盡的比賽在第二塊警示(VertexType2是從來沒有匹配),但沒有一個。
實際上,在2.9.0-RC3之前的Scala編譯器產生了一個我期望看到的警告,但是以RC3開頭的版本(包括2.9.0和2.9.0-1)沒有,這相當混亂。
倍數:這已被固定在斯卡拉2.10。 (在Scala 2.9.x中出現了迴歸) – gourlaysama 2013-01-31 16:16:51