我相信很长一段时间,这两个方案是等价的:为什么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