Is there a difference between classOf[String].isInstance("42")
and "42".isInstanceOf[String]
?
If yes, can you explain ?
For reference types (those that extend AnyRef
), there is no difference in the end result. isInstanceOf
is however much encouraged, because it's more idiomatic (and likely much more efficient).
For primitive value types, such as numbers and booleans, there is a difference:
scala> val x: Any = 5
x: Any = 5
scala> x.isInstanceOf[Int]
res0: Boolean = true
scala> classOf[Int].isInstance(x)
res1: Boolean = false
That is because primitive value types are boxed when upcasted to Any
(or AnyVal
). For the JVM, they appear as java.lang.Integer
s, not as Int
s anymore. The isInstanceOf
knows about this and will do the right thing.
In general, there is no reason to use classOf[T].isInstance(x)
if you know right then what T
is. If you have a generic type, and you want to "pass around" a way to test whether a value is of that class (would pass the isInstanceOf
test), you can use a scala.reflect.ClassTag
instead. ClassTag
s are a bit like Class
es, except they know about Scala boxing and a few other things. (I can elaborate on ClassTag
s if required, but you should find info about them elsewhere.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With