Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


Share this Page URL
Help

Chapter 11: Scala's Hierarchy > 11.2 How primitives are implemented - Pg. 213

S ECTION 11.2 · How primitives are implemented Java platform AnyRef is in fact just an alias for class java.lang.Object . So classes written in Java as well as classes written in Scala all inherit from AnyRef . 2 One way to think of java.lang.Object , therefore, is as the way AnyRef is implemented on the Java platform. Thus, although you can use Object and AnyRef interchangeably in Scala programs on the Java platform, the recommended style is to use AnyRef everywhere. Scala classes are different from Java classes in that they also inherit from a special marker trait called ScalaObject . 11.2 How primitives are implemented How is all this implemented? In fact, Scala stores integers in the same way as Java: as 32-bit words. This is important for efficiency on the JVM and also for interoperability with Java libraries. Standard operations like addition or multiplication are implemented as primitive operations. However, Scala uses the "backup" class java.lang.Integer whenever an integer needs to be seen as a (Java) object. This happens for instance when invoking the toString method on an integer number or when assigning an integer to a variable of type Any . Integers of type Int are converted transparently to "boxed integers" of type java.lang.Integer whenever necessary. All this sounds a lot like auto-boxing in Java 5 and it is indeed quite similar. There's one crucial difference, though, in that boxing in Scala is much less visible than boxing in Java. Try the following in Java: // This is Java boolean isEqual(int x, int y) { return x == y; } System.out.println(isEqual(421, 421)); You will surely get true . Now, change the argument types of isEqual to java.lang.Integer (or Object , the result will be the same): 2 The reason the AnyRef alias exists, instead of just using the name java.lang.Object , is because Scala was designed to work on both the Java and .NET platforms. On .NET, AnyRef is an alias for System.Object . 213