繁体   English   中英

asInstanceOf [X]和toX之间的值类型有何不同?

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

我使用IntelliJ的能力将Java代码转换为Scala代码,这些代码通常运行良好。

似乎IntelliJ通过调用asInstanceOf替换了所有强制转换。

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

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

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

...

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

那么, 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
                                  ^

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM