Singletons are objects that can have only a single instance throughout the lifetime of a program. Singleton pattern ensures that a class provides only one instance with global access to that instance. Scala provides different ways to create and use Singletons. Let’s discuss four methods:
1. Object: The most straightforward way to create Singleton patterns in Scala is by using ‘object‘. An object in Scala is a class with a single instance. When the object is declared, Scala automatically creates an instance and makes it globally accessible. Here is an example:
object Singleton {
def greet(): Unit = {
println("Hello, I am a Singleton!")
}
}
// Usage
Singleton.greet()
2. Class and Companion Object: Using companion objects is another way of creating Singletons. Create a class that holds the logic but restricts the direct construction of an instance via ‘private constructor‘. Then define a companion object for the class that holds the single instance and provides a global access point.