A simple case:
class ValueClass[T](val x :T) extends AnyVal val ints = Seq(42) val values = ints.asInstanceOf[ValueClass[Int]] val h = values.head
Obviously, this is plain wrong and throws a
ClassCastException. However, it would be very beneficial and made value classes considerably more useful if it worked. Aside from the collection case, where the ‘only’ issue is performance, there is also a case of implementing a generic interface with a value class as the type argument, which results in a bytecode clash of the erased, ‘bridge’ method signature inherited from the base type and the actual implementation. It simply cannot be done, AFAIK.
On first glance however, I can’t see why it couldn’t work; why the compiler, when inserting the cast from the erased object to a value class, couldn’t verify that the object is not of class
ValueClass and treat it as the backing value of that class? There is an argument that in a generic context (i.e., an erased type instead of
Int here), this wouldn’t offer any type safety whatsoever. But this delayed casting error is no different from how generics work in JVM anyway.