我相信很長一段時間,這兩個方案是等價的:爲什麼Scala的模式匹配不等同於isInstanceOf
if (myVar.isInstanceOf[MyType]) myVar.asInstanceOf[MyType].doSomething
和
myVar match {
case my : MyType => my.doSomething
case _ => {}
}
但是突然我發現,我得到的類型錯誤,同時嘗試將Number
值與Double
類型匹配,但asInstanceOf[Double]
正常工作。跆拳道正在發生?
爲階REPL
val d = 3.5
val n : Number = d
n.isInstanceOf[Double]
簡單的例子正常工作:
Boolean = true
但
n match {
case x : Double => println("double")
case _ => println("not a double")
}
產生錯誤類型:
:11: error: pattern type is incompatible with expected type;
found : Double
required: Number
case x : Double => println("double")
'? – marios