Reputation: 27395
I wrote the following very simple test:
import scala.collection.immutable.HashSet
class Test {
def m() = {
var s = new HashSet[Int]
s = s + 1
}
}
And figured out that it compiles to this code:
public class Test {
public void m();
Code:
0: new #12 // class scala/collection/immutable/HashSet
3: dup
4: invokespecial #15 // Method scala/collection/immutable/HashSet."<init>":()V
7: astore_1
8: aload_1
9: iconst_1
10: invokestatic #21 // Method scala/runtime/BoxesRunTime.boxToInteger:(I)Ljava/lang/Integer;
13: invokevirtual #25 // Method scala/collection/immutable/HashSet.$plus:(Ljava/lang/Object;)Lscala/collection/immutable/HashSet;
16: astore_1
17: return
public Test();
Code:
0: aload_0
1: invokespecial #30 // Method java/lang/Object."<init>":()V
4: return
}
As you can see, 1
is boxed before creating a new immutable set with 1 element. Why is it boxed. Int extends AnyVal
, not AnyRef
.
Upvotes: 4
Views: 72
Reputation: 44918
Exactly, Int extends AnyVal
, not AnyRef
. But the immutable HashSet[A]
has A
as parameter, which is not specialized for primitive types, that is, it is not @specialized(Int) A
or anything like that, so it can deal only with reference types that extend AnyRef
, the primitive types must be boxed. This, fortunately, is hidden by the Scala compiler.
Upvotes: 6