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] ...
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