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

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

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