Singletons and Companions
Scala takes a significant departure from Java in how it deals with static fields and methods. Furthermore, it has first-class support for singleton objects. Let’s explore singletons and companions, and see how static is handled in Scala.
Singleton Object
Singleton is a popular pattern discussed in Design Patterns: Elements of Reusable Object-Oriented Software [GHJV95] by Gamma et al. A singleton is a class that has only one instance. We use singletons to represent objects that act as a central point of contact for certain operations such as database access, object factories, and so on.
It turned out that the singleton pattern is easy to understand but hard to implement in Java—see Joshua Bloch’s Effective Java [Blo08] ...
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.