Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are primitive types such as Int erased to Object in Scala?

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?

like image 883
Scott Morrison Avatar asked Jun 23 '12 06:06

Scott Morrison


1 Answers

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.

like image 144
Daniel C. Sobral Avatar answered Oct 16 '22 01:10

Daniel C. Sobral