简体   繁体   English

为什么Scala模式匹配不等于isInstanceOf

[英]Why scala pattern matching is not equivalent to isInstanceOf

I believed for a long time that this two constructions is equivalent: 我长期以来认为这两种构造是等效的:

if (myVar.isInstanceOf[MyType]) myVar.asInstanceOf[MyType].doSomething

and

myVar match {
  case my : MyType => my.doSomething
  case _ => {}
}

But suddenly I've found that I get type error while trying to match Number value to the Double type, but asInstanceOf[Double] works fine. 但是突然我发现尝试将Number值匹配到Double类型时遇到类型错误,但是asInstanceOf[Double]可以正常工作。 WTF is happening? WTF正在发生?


simple example for scala REPL scala REPL的简单示例

val d = 3.5
val n : Number = d
n.isInstanceOf[Double]

works fine: 工作正常:

Boolean = true

but

n match {
  case x : Double => println("double")
  case _ => println("not a double")
}

produces type error: 产生类型错误:

:11: error: pattern type is incompatible with expected type;
found   : Double
required: Number
          case x : Double => println("double")

scala.Double is not inherited from java.lang.Number but from AnyVal . scala.Double不是从java.lang.Number继承,而是从AnyVal继承。 You want to match on java.lang.Double : 您要在java.lang.Double上进行匹配:

n match {
  case x : java.lang.Double => println("double")
  case _                    => println("not a double")
}

When using 使用时

val d = 3.5
val n : Number = d  // implicit conversion from scala.Double to java.lang.Double

scala.Double is implicitly converted to java.lang.Double during assignment to n scala.Double赋值给n隐式转换为java.lang.Double

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM