对于值类型,asInstanceOf[X] 和 toX 之间有什么区别吗?

发布于 2024-10-08 19:37:04 字数 242 浏览 5 评论 0原文

我使用 IntelliJ 将 Java 代码转换为 Scala 代码的功能,通常效果很好。

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

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

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 asInstanceOf.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风柔一江水 2024-10-15 19:37:04

我不知道有这样的案例。 来检查发出的字节码是否相同,

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

...

以获取在每种情况下发出的完全相同的字节码。

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.

昔日梦未散 2024-10-15 19:37:04

嗯,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
                                  ^

Well, toInt and toLong are not casts. The correct conversion of type casting is asInstanceOf indeed. For example:

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
                                  ^
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文