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

Package Objects

By convention Java packages contain only interfaces, classes, enumerations, and annotation types. Scala goes a step further: packages can also have variables and functions. These are placed in special singleton objects called package objects.

If you find yourself creating a class only to hold a set of shared methods among other classes in a package, then a package object will remove that extra burden to create and then repeatedly reference that extra class. Let’s explore this with an example.

First let’s create an example using singleton and then convert it to a package class so we can get a good feel for its benefits.

In this example we will reuse the Currency enumeration and the Money class we created earlier. Here’s a

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