3

I'm confused as how isInstanceOf works in Scala. If I do something like this:

val x: Int = 5
x.isInstanceOf[Int]

Given that Scala does type erasure, shouldn't the JVM remove all type information during runtime?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
PsychoMantis
  • 45
  • 1
  • 3

1 Answers1

10

It's not all type information, just information about generic types. Consider this:

scala> val l = List("foo")
l: List[String] = List(foo)

scala> l.isInstanceOf[List[String]]
res0: Boolean = true

scala> l.isInstanceOf[List[Int]]
<console>:9: warning: fruitless type test: a value of type List[String] cannot also be a List[Int] (the underlying of List[Int]) (but still might match its erasure)
              l.isInstanceOf[List[Int]]
                            ^
res1: Boolean = true

They both return true, because the erased type is List.

IonuČ› G. Stan
  • 176,118
  • 18
  • 189
  • 202