Aladdin - Scala Bugtracking
[#431] project: compiler priority: low category: bug
submitter assigned to status date submitted
Michel Martin won't fix 2005-05-19 08:59:09.0
subject asInstanceOf does not perform coercion in some cases
code
object Main with Application {
  def f1[T](x: Any): T = x.asInstanceOf[T];
  Console.println(f1[Float](42));  // this works

  def f2(x: Any): Float = x.asInstanceOf[Float];
  Console.println(f2(42));        // this crashes
}
what happened
The call to f1 works (if you enable run time types, that is), while the call to f2, wh\
ich is equivalent, crashes with a ClassCastException.
what expected

No crash.

This problem is due to the double meaning of asInstanceOf: for value types, it performs coercion, for other types it performs type casts. I handle this correctly in my run time types, as shown by function f1. What is not handled correctly is the case where the selector has type Any and the type argument is a value type, like in f2. In such cases, the compiler should produce more complex code than it does now.

[back to overview]
Changes of this bug report
Martin  edited on  2006-05-08 10:30:33.0
Noy applicable to Scala 2 with erasure semantics