值类型的asInstanceOf [X]和toX之间有什么区别? [英] Any differences between asInstanceOf[X] and toX for value types?

查看:143
本文介绍了值类型的asInstanceOf [X]和toX之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

似乎IntelliJ替换了所有对 asInstanceOf 。

It seems that IntelliJ replaced all casts with calls to asInstanceOf.

asInstanceOf [Int] 是否有效? code> asInstanceOf [Long] 等,对于不能用 toInt toLong替换的值类型,...?

Is there any valid usage of asInstanceOf[Int], asInstanceOf[Long] etc. for value types which can't be replaced by toInt, toLong, ...?

推荐答案

我不知道有这种情况。您可以通过编译类似

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

并使用 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

...

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

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

这篇关于值类型的asInstanceOf [X]和toX之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆