How did these all come to be achieved? In fact, Scala stores integers in the same way as Java: use it as a 32-bit word. This is important for efficiency on the JVM and for interoperability with the Java library. Standard operations, such as addition or multiplication, are implemented as primitive operations. However, when integers need to be treated as (Java) objects, Scala uses the "Backup" class Java.lang.Integer. This is done if the ToString method is invoked on an integer or when an integer is assigned to a variable of any type. When needed, integers of type int can be transparently converted to "boxed integers" of the Java.lang.Integer type.
All of this sounds like automatic boxing in the JAVA5 and they really look alike. One key difference, though, is that Scala's boxing is less visible than in Java. Try the following Java code:
Java Code
boolean isequal (int x,int y) {return
x = = y;
}
System.out.println (IsEqual (421,421));
Of course you will get true. Now, change the isequal argument type to Java.lang.Integer (or object, and the result is the same):
Java Code
Boolean isequal (Integer x, integery) {return
x = = y;
}
System.out.println (IsEqual (421,421));
You'll find that you've got false! The reason is that several 421 were boxed two times, so that the parameters x and Y are two different objects.
The result is false because the = = = = refers to equality on the reference type, and the integer is a reference type. This is an aspect of the presentation that Java is not a pure object-oriented language. We can clearly observe the difference between the original type and the reference type.
Now try the same experiment in Scala:
Scala>def isequal (x:int, y:int) = x = = y
isequal: (int,int) Boolean
scala>isequal (421,421)
Res10:boo Lean = True
scala>def isequal (x:any, y:any) = x = = y
isequal: (any,any) Boolean
scala>isequal (421,421 )
Res11:boolean = True