【问题标题】:Any differences between asInstanceOf[X] and toX for value types?asInstanceOf[X] 和 toX 对于值类型有什么区别吗?
【发布时间】:2011-05-30 13:28:24
【问题描述】:

我使用 IntelliJ 将 Java 代码转换为 Scala 代码的能力,这通常工作得很好。

似乎 IntelliJ 用对 asInstanceOf 的调用替换了所有强制转换。

对于不能被toInttoLong、...替换的值类型,asInstanceOf[Int]asInstanceOf[Long] 等是否有任何有效用法?

【问题讨论】:

    标签: java scala casting language-features


    【解决方案1】:

    我不知道有任何此类情况。您可以通过编译类似的类来检查自己发出的字节码是否相同

    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]
    }
    

    并使用javap -c Conv 获取

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

    您可以看到在每种情况下都发出完全相同的字节码。

    【讨论】:

      【解决方案2】:

      好吧,toInttoLong 不是 演员表。类型转换的正确转换确实是asInstanceOf。例如:

      scala> val x: Any = 5
      x: Any = 5
      
      scala> if (x.isInstanceOf[Int]) x.asInstanceOf[Int] + 1
      res6: AnyVal = 6
      
      scala> if (x.isInstanceOf[Int]) x.toInt + 1
      <console>:8: error: value toInt is not a member of Any
             if (x.isInstanceOf[Int]) x.toInt + 1
                                        ^
      

      【讨论】:

      • 是的,在这方面你是对的。 toInt 之类的东西不一定存在于AnyVal 之外的对象上,但asInstanceOf 确实存在。
      猜你喜欢
      • 2010-12-11
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 2011-03-25
      • 1970-01-01
      • 1970-01-01
      • 2010-10-02
      • 2011-01-14
      相关资源
      最近更新 更多