为什么在Scala中将Int等原始类型擦除为Object? [英] Why are primitive types such as Int erased to Object in Scala?

查看:43
本文介绍了为什么在Scala中将Int等原始类型擦除为Object?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Scala 中,

{ x: Option[Int] =>X }.getClass.getMethod("申请", classOf[Option[_]]).getGenericParameterTypes

返回Array(scala.Option).我最初期待看到 Array(scala.Option),但我看到 scala.Int 是一个值类(扩展 AnyVal)'其实例未表示作为底层主机系统的对象'.

不过,我仍然不明白对Object 的擦除.难道它不是更有用的 java.lang.Integer 吗?

解决方案

难道它不是更有用的java.lang.Integer吗?

是的,曾经也是这样.不幸的是,这会导致类型签名损坏.也就是说,如果将 Int 擦除为 java.lang.Integer,则不可能在所有情况下都生成正确的字节码.

没有关于此的单一票证或提交,但改变此特定行为的是scala/bug#4214,在此提交中.>

In Scala,

{ x: Option[Int] => x }
   .getClass
   .getMethod("apply", classOf[Option[_]])
   .getGenericParameterTypes

returns Array(scala.Option<java.lang.Object>). I'd initially been expecting to see instead Array(scala.Option<scala.Int>), but I see that scala.Int is a value class (extends AnyVal) 'whose instances are not represented as objects by the underlying host system'.

I still don't understand the erasure to Object, though. Couldn't it be the much more useful java.lang.Integer?

解决方案

Couldn't it be the much more useful java.lang.Integer?

Yes, and that was even the case, once. Unfortunately, that leads to broken type signatures. That is, it is impossible to generate correct bytecode in all situations if Int is erased to java.lang.Integer.

There isn't a single ticket or commit about this, but the one that changed this particular behavior is scala/bug#4214, in this commit.

这篇关于为什么在Scala中将Int等原始类型擦除为Object?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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