今天在看MLlib的源碼時,看到Vector的聲明是 sealed trait sealed
,很好奇這個
有什麼作用,與是搜到了這個文章:
http://www.cnblogs.com/rollenholt/p/4192758.html
試驗了下,這個sealed就是保證你在match的時候需要把所有可能出現的情況都寫出來。如果漏掉一個,就會報編譯出錯:
比如下面的代碼,聲明了兩個trait,其中Test2是sealed聲明:
sealed trait Test2{}
trait Test1{}
case class A1 extends Test1{}
case class B1 extends Test1{}
case class C1 extends Test1{}
case class A2 extends Test2{}
case class B2 extends Test2{}
case class C2 extends Test2{}
然後做個測試:
object TraitTest {
def main(args: Array[String]) {
val x:Test1 = new B1()
x match {
case x @ A1() => println("A1")
case x @ B1() => println("B1")
}
}
}
這樣是沒什麼問題的。
object TraitTest1 {
def main(args: Array[String]) {
val x:Test2 = new B2()
x match {
case x @ A2() => println("A2")
case x @ B2() => println("B2")
// case x @ C2() => println("C2")
}
}
}
如果注釋沒有打開,就會報下面的錯誤:
Warning:(30, 5) match may not be exhaustive.
It would fail on the following input: C2()
x match {
^
在Spark MLlib中,它是這樣用的:
sealed trait Vector extends Serializable {
...
override def equals(other: Any): Boolean = {
other match {
case v2: Vector =>
if (this.size != v2.size) return false
(this, v2) match {
case (s1: SparseVector, s2: SparseVector) =>
Vectors.equals(s1.indices, s1.values, s2.indices, s2.values)
case (s1: SparseVector, d1: DenseVector) =>
Vectors.equals(s1.indices, s1.values, 0 until d1.size, d1.values)
case (d1: DenseVector, s1: SparseVector) =>
Vectors.equals(0 until d1.size, d1.values, s1.indices, s1.values)
case (_, _) => util.Arrays.equals(this.toArray, v2.toArray)
}
case _ => false
}
}
}
這樣能有效的避免遺漏可能出現的情況!
作者:xingoo
出處:http://www.cnblogs.com/xing901022
本文版權歸作者和部落格園共有。歡迎轉載,但必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接!