The problem is that JVM doesn't support intersection types, so there is no obvious runtime equivalent to asInstanceOf[Int with Foo]
. This is basically the same issue as asInstanceOf[T]
, where T
is a generic parameter (both in Scala and equivalent Java): you also have the cast which appears to succeed at runtime but actually inserts casts in later code which uses methods of T
.
One possibility would be to compile the cast to Int with Foo
as two casts to Int
and to Foo
, but this doesn't quite work in general (e.g. when there is no runtime cast to Foo
itself, or when the value is passed to methods which take Int with Foo
).