Scala Singletons
Singleton objects in Scala
Often in software modeling we need to represent an entity that it does not make sense to have more than one instances throughout program execution. We call these objects singletons. Typically, singletons are modeled using static functions. Scala does not support static functions. Instead we use the object
construct [1].
An object defines a single instance of a class with the features we want. For example
object Counter{
private var theCounter = 0
def getNewCounter : Int = {theCounter +=1; theCounter}
}
When the application requires a new counter, simply calls Counter.getNewCounter
println("New counter " + Counter.getNewCounter)
The constructor of an object is executed when the object is first used [1]. If an object is never used, its constructor is, obviously, not executed [1].
An object can have all the features of a class, including extending other
classes or traits [1]. However, an object
cannot have a constructor with parameters.
- Cay Horstmann,
Scala for the Impatient 1st Edition