Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between isInstance and isInstanceOf

Tags:

scala

Is there a difference between classOf[String].isInstance("42") and "42".isInstanceOf[String] ?

If yes, can you explain ?

like image 667
Yann Moisan Avatar asked Oct 02 '14 20:10

Yann Moisan


1 Answers

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.Integers, not as Ints 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. ClassTags are a bit like Classes, except they know about Scala boxing and a few other things. (I can elaborate on ClassTags if required, but you should find info about them elsewhere.)

like image 172
sjrd Avatar answered Sep 24 '22 23:09

sjrd