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

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.