The current behavior of asInstanceOf
without an explicit type parameter is (a) useless and (b) non-standard.
@ val x: String = ("hello": CharSequence).asInstanceOf
java.lang.ClassCastException: class java.lang.String cannot be cast to class scala.runtime.Nothing$ (java.lang.String is in module java.base of loader 'bootstrap'; scala.runtime.Nothing$ is in unnamed module of loader 'app')
ammonite.$sess.cmd2$.<clinit>(cmd2.sc:1)
@ def cast[T](x: Any): T = x.asInstanceOf[T]
defined function cast
@ val x: String = cast("hello": CharSequence)
x: String = "hello"
Apart from behaving totally different from any other generic method (e.g. the def cast
shown above), this makes it considerably less useful than it could be. Because if you want to cast something you need to spell out the explicit type every time, which is often tedious or even impossible e.g. if the expected type is _$1
such as in the error below:
[error] found : variable.value.type (with underlying type _$1)
[error] required: _$1
[error] for ((variable, i) <- flattened.params.iterator.zipWithIndex) variable.mappedType.put(statement, i + 1, variable.value)
[error]
A trivial cast
function as defined above does the right thing due to type inference, even for these “impossible” types which cannot be spelled out in code.
Can we fix asInstanceOf
to infer types the right way? That would both make it a lot more well-behaved, and also simplify a lot of scenarios where spelling out the type you want to cast to is either verbose or totally impossible. There are basically no scenarios where asInstanceOf
blowing up 100% of the time with a ClassCastException
is the desired behavior, so we wouldn’t be breaking anything that isn’t already broken