I have been playing with basic Scala data types. I noticed that the scala.Any
class defines the method asInstanceOf[T0]: T0
from here The API has i
I think you've confused the terms "cast" and "convert".
The standard conversion methods begin with to
, e.g. 20d.toInt
will convert a value 20
of type Double
a value 20 of type Int
.
asInstanceOf
on the other hand is a special type casting method. All it does is informs the compiler that the value is of the type specified in its parameter, if during runtime the value on which you call this method does not match with what you specified in the type parameter, you'll get an exception thrown. I.e. in a.asInstanceOf[B]
the provided value a
must be of a type B
or inherit from it - otherwise you'll get an exception.