Scala Classes for Java Primitives

Java presents a split view of the world—it treats primitives, such as int and double, differently from objects. Since Java 5, to a limited extent, we can treat primitives like objects using autoboxing. However, Java doesn’t permit method calls like 2.toString() on primitives. Plus autoboxing involves casting overhead and has a few negative consequences.

Unlike Java, Scala treats all types as objects. This means you can call methods on literals, just like you can call methods on objects. In the following code, we create an instance of Scala’s Int and send it to the ensureCapacity method of java.util.ArrayList, which expects a Java primitive int.

FromJavaToScala/ScalaInt.scala
 
class​ ScalaInt {
 
def​ playWithInt() ...

Get Pragmatic Scala now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.