Singleton Object in Scala

Scala Tutorial

Senthil Nayagan
2 min readMar 11, 2019
Kovalam Beach, South India

What is Singleton?

A singleton in general is a class that allows only a single instance/object of itself to be created and gives access to that created instance.

Hence, singleton restricts the instantiation of a class to one.

Use case

Exactly one object is needed to maintain that instance across systems and remains constant.

Once the object is created and the same will be returned for all subsequent object requests.

Scala’s Singleton Object

By design, Scala is a pure object-oriented language and hence we can’t create static fields and methods in a Scala class.

However, we can create singleton objects in Scala where fields or methods defined in a singleton can be accessed like static members in Java.

Rule of Convenience: Methods and values that aren’t associated with instances of a class belong in singleton objects.

Scala has built-in implementation of singleton without much more work to do.

In Scala, the singleton object is denoted by using the keyword object instead of class.

package tutorialobject SingletonObject {
// This method returns nano time as long integer type.
def time(): Long = {
System.nanoTime
}
}

Here, time method is available globally and can be referred to or imported as tutorial.SingletonObject.time.

Having said that, singleton objects defines a single-use class.

Singleton objects can’t directly be instantiated Scala will instantiate the object on its first use and next time onwards, it uses the same instance.

A singleton object can extend classes and traits.

Singleton Object Use Cases

We use singleton object as a collection of static methods.

Use singleton object when we need one and only instance of the class.

Classes vs. Singleton Objects

A difference between classes and singleton objects is that singleton objects cannot take parameters, whereas classes can — as we can’t instantiate a singleton object with the new keyword, there is no way to pass parameters to it.

Standalone Object

A singleton object that does not share the same name with a companion class is called a standalone object.

We use standalone object as an entry point to a Scala application.

--

--

Senthil Nayagan
Senthil Nayagan

Written by Senthil Nayagan

I am a Data Engineer by profession, a Rustacean by interest, and an avid Content Creator.

No responses yet