Any differences between asInstanceOf[X] and toX for value types?

后端 未结 2 902
不知归路
不知归路 2021-02-19 11:56

I used IntelliJ\'s ability to convert Java code to Scala code which generally works quite well.

It seems that IntelliJ replaced all casts with calls to asInstanceO

2条回答
  •  余生分开走
    2021-02-19 12:29

    I do not know of any such cases. You can check yourself that the emitted bytecode is the same by compiling a class like

    class Conv {
      def b(i: Int) = i.toByte
      def B(i: Int) = i.asInstanceOf[Byte]
      def s(i: Int) = i.toShort
      def S(i: Int) = i.asInstanceOf[Short]
      def f(i: Int) = i.toFloat 
      def F(i: Int) = i.asInstanceOf[Float]  
      def d(i: Int) = i.toDouble
      def D(i: Int) = i.asInstanceOf[Double]
    }
    

    and using javap -c Conv to get

    public byte b(int);
      Code:
       0:   iload_1
       1:   i2b
       2:   ireturn
    
    public byte B(int);
      Code:
       0:   iload_1
       1:   i2b
       2:   ireturn
    
    ...
    

    where you can see that the exact same bytecode is emitted in each case.

提交回复
热议问题