Overview

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

Singletons

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} 
}
defined object Counter

When the application requires a new counter, simply calls Counter.getNewCounter

println("New counter " + Counter.getNewCounter)
New counter 1

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.

References

  1. Cay Horstmann, Scala for the Impatient 1st Edition