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
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access