5
votes

I was wondering, why AnyVal can not be used in an isInstanceOf check ? What is the reason behind this behavior ?

scala> val c = 't'
c: Char = t

scala> c.isInstanceOf[AnyVal]
<console>:12: error: type AnyVal cannot be used in a type pattern or isInstanceO
f test
             c.isInstanceOf[AnyVal]
1
I guess, this is related too scala-lang.org/node/3271om-nom-nom
Thanks, but the provided Links does not tell me why it is the way is is. I do not want to check a primitive type, I just want to know, why AnyVal can not be used ? What is the background ? What is the rule behind this behavior ?John Threepwood
Doesn't look like a duplicate to me. One is asking how to do it, the other (this one) is asking why it is not possible.Daniel C. Sobral

1 Answers

11
votes

AnyVal does not exist anymore at runtime. Only at compile-time. In other words, it's just a compiler "trick" to consider the JVM primitives as first-class objects.

However, the isInstanceOf method is executed at runtime, so it cannot work. Hence the compiler error.