Singleton objects

Singleton objects

When you replace the keyword class by object, you define a singleton object. A singleton definition defines a new type like a class does, but only one single object of this type can be created—therefore the name "singleton".

Here is a simple singleton definition:

object MySingleton {
  println("Creating MySingleton")

  var sum = 0                    
  def add(b: Int) { 
    sum += b
The println statement here is part of the singleton's constructor. The singleton has one field sum, and one method add.

The definition will create an object of this type, and assign the name MySingleton to it. The construction of the object happens the first time the object is used (so if you define a singleton and never use it, it will not be constructed at all).

scala> MySingleton.add(5)
Creating MySingleton
scala> MySingleton.add(7) 
scala> MySingleton.sum    
res1: Int = 12
Note in particular that the name of a singleton is not a type name, but the name of an object!

You can define both a class and a singleton object with the same name. In this case, the singleton is called the companion object of the class. A companion object is allowed to use the private fields and private methods of a class.