how to use asInstanceOf properly in Scala

后端 未结 3 1650
自闭症患者
自闭症患者 2021-01-04 08:53

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

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-04 09:20

    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.

提交回复
热议问题