Scala - Singleton Object



We will discuss the concept of singleton objects in Scala programming in chapter. Singleton objects are unique instances of a class that cannot be instantiated more than once. These are used to represent global state and utility functions.

Singleton Objects in Scala

Singleton objects are created using the object keyword instead of class. Singleton objects can have methods and values that are shared across the entire application. It can also extend classes and traits, just like regular classes.

Syntax

The syntax of the singleton object is -

object SingletonName {
  // Fields and methods
}

Example

The following example shows a simple singleton object in Scala programming.

object Greeting {
  def sayHello(name: String): Unit = {
    println(s"Hello, $name!")
  }
}

object Demo {
  def main(args: Array[String]) = {
    Greeting.sayHello("tutorialspoint")  // Accessing the singleton object method
  }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Hello, tutorialspoint!

In the example, the Greeting singleton object has method sayHello that prints a greeting message. The Demo object has the main method. It accesses the sayHello method of the Greeting singleton object.

Companion Objects

Companion object is a singleton object that shares the same name as a class. Companion object is defined in the same source file. Companion objects can access the private fields and methods of their companion class.

Syntax

The syntax of the companion objects is -

class ClassName {
  // Class fields and methods
}

object ClassName {
  // Companion object fields and methods
}

Example

The following example shows the use of a companion object in Scala programming.

class Counter {
  private var count: Int = 0

  def increment(): Unit = { count += 1 }
  def currentCount: Int = count
}

object Counter {
  def reset(counter: Counter): Unit = {
    counter.count = 0  // Accessing private field of the companion class
  }
}

object Demo {
  def main(args: Array[String]) = {
    val counter = new Counter
    counter.increment()
    counter.increment()
    println(s"Current count: ${counter.currentCount}")  // Output: 2
    Counter.reset(counter)
    println(s"Current count after reset: ${counter.currentCount}")  // Output: 0
  }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Current count: 2
Current count after reset: 0

In the example, the Counter class has a private field count and methods to modify it. The companion object Counter defines a method reset that can access and modify the private field count of the Counter class. The Demo object uses the Counter class and its companion object.

Singleton Objects in Practice

Singleton objects are used to define utility methods and constants, manage global state, and implement the Singleton design pattern.

Example: Utility Methods

object MathUtils {
  def add(a: Int, b: Int): Int = a + b
  def subtract(a: Int, b: Int): Int = a - b
}

object Demo {
  def main(args: Array[String]) = {
    println(s"5 + 3 = ${MathUtils.add(5, 3)}")  // Output: 8
    println(s"5 - 3 = ${MathUtils.subtract(5, 3)}")  // Output: 2
  }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

5 + 3 = 8 
5 - 3 = 2

Example: Global State

object Config {
  var applicationName: String = "Tutorialspoint"
  var version: String = "1.0.0"
}

object Demo {
  def main(args: Array[String]) = {
    println(s"Application Name: ${Config.applicationName}")
    println(s"Version: ${Config.version}")

    // Modify global state
    Config.version = "1.1.0"
    println(s"Updated Version: ${Config.version}")
  }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Application Name: Tutorialspoint
Version: 1.0.0
Updated Version: 1.1.0

Singleton Design Pattern

Singleton design pattern ensures that a class has only one instance and provides a global point of access to it. Singleton objects in Scala inherently follow this pattern.

Example

object Logger {
  def log(message: String): Unit = {
    println(s"Log: $message")
  }
}

object Demo {
  def main(args: Array[String]) = {
    Logger.log("This is a log message.")  // Accessing the singleton object
  }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Log: This is a log message.

In the example, the Logger singleton object has a log method that prints log messages. The Demo object uses the Logger singleton object.

Scala Singleton Object Summary

  • Singleton objects are unique instances of a class. Singleton objects cannot be instantiated more than once.
  • Singleton objects are defined using the object keyword.
  • Companion objects share the same name as a class. Singleton objects can access the private fields and methods of their companion class.
  • Singleton objects are useful for defining utility methods, managing global state, and implementing the Singleton design pattern.
Advertisements