How is the original type of Scala implemented

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.