簡體   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