5

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]
John Threepwood
  • 15,593
  • 27
  • 93
  • 149
  • Related: http://stackoverflow.com/questions/10416658 – Tomasz Nurkiewicz Jun 17 '12 at 11:20
  • I guess, this is related too http://www.scala-lang.org/node/3271 – om-nom-nom Jun 17 '12 at 11:46
  • possible duplicate of [How to test a value on being AnyVal?](http://stackoverflow.com/questions/10416658/how-to-test-a-value-on-being-anyval) – oxbow_lakes Jun 17 '12 at 12:08
  • 1
    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 Jun 17 '12 at 12:15
  • @JohnThreepwood Sorry, I missed the point. I cannot undo my close vote, but here comes an answer for your question. – paradigmatic Jun 17 '12 at 14:38
  • [Some information](http://stackoverflow.com/questions/2335319/what-are-the-relationships-between-any-anyval-anyref-object-and-how-do-they-m) to Any, AnyVal, AnyRef etc. – kiritsuku Jun 17 '12 at 15:04
  • 1
    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 Jun 17 '12 at 18:33

1 Answers1

11

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.

paradigmatic
  • 40,153
  • 18
  • 88
  • 147
  • I am not sure if this is ugly or nice. – Karel Bílek Jun 17 '12 at 19:50
  • 1
    Well, `isInstanceOf` is considered as ugly in Scala ;-) You should rely on the type system to get that kind of information at compile time. – paradigmatic Jun 17 '12 at 20:42
  • I'm probably being very thick, but I don't understand the logic of this answer. You don't in general disallow boolean methods just because the answer is always "false". And `1.isInstanceOf[Int]` works fine... And the answers to the linked "duplicate" show that such a method is possible at runtime. – Luigi Plinge Jun 17 '12 at 20:45
  • The accepted answer in http://stackoverflow.com/questions/10416658/how-to-test-a-value-on-being-anyval relies on implicit evidence, which is also resolved at compile time. – paradigmatic Jun 18 '12 at 05:24
  • I just tried to `javap` on `1.isInstanceOf[Int]`. It relies on boxing and checks at runtime if the boxed 1, is an instance of `java.lang.Integer`. – paradigmatic Jun 18 '12 at 05:44