简体   繁体   中英

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. WTF is happening?


simple example for 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 . You want to match on 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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