O'Reilly logo

Pragmatic Scala by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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() ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required