r/scala•
valenterry

Trouble with asInstanceOf and isInstanceOf

I thought I understand how those functions work at compiletime/runtime, but it seems I really don't. Consider this code:

class A
trait T

val newAwithT: A with T = new A with T
newAwithT.isInstanceOf[A] // = true
newAwithT.isInstanceOf[T] // = true
newAwithT.isInstanceOf[A with T] // = true

val aAsInstanceOf: A with T = (new A).asInstanceOf[A with T]
aAsInstanceOf.isInstanceOf[A] // = true
aAsInstanceOf.isInstanceOf[T] // = false
aAsInstanceOf.isInstanceOf[A with T] // = true

(https://scalafiddle.io/sf/DH3UYDK/0)

So, newAwithT.isInstanceOf[T] is true, but (new A).asInstanceOf[A with T].isInstanceOf[T] is not. I think this happens because in the latter case we are just "tagging" A with T so there is no information of T at runtime. Am I correct here?

However, how does isInstanceOf[A with T] work and why is it true in the second case even though isInstanceOf[T] returns false? I can only assume that Scala is creating a third type A with T which is not in the inheritance chain with T.

Can someone enlighten me?

Posted Jun 17, 2017, 10:14 AM UTC · edited

1615
Loading comments…