how to use asInstanceOf properly in Scala

后端 未结 3 1667
自闭症患者
自闭症患者 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:10

    Java (and Scala) allows you to cast a primitive double to int (in Scala's case, Double to Int). On the other hand, you cannot cast java.lang.Double to java.lang.Int.

    When you declare the Double as an Any, you're explicitly asking the compiler to forget that you gave it a Double. Therefore, in order to support the Any interface, the compiler is storing the value as a boxed double (i.e., java.lang.Double).

    The behavior does seem confusing, but it's not a bug. According §12.1 of the Scala Language Spec:

    The test x.asInstanceOf[T] is treated specially if T is a numeric value type (§12.2). In this case the cast will be translated to an application of a conversion method x.toT (§12.2.1).

提交回复
热议问题