How do you define a singleton object in Scala?

Instruction: Explain the concept of a singleton object in Scala and provide an example of its declaration.

Context: This question tests the candidate's understanding of the object keyword in Scala and its use for creating singleton instances, including their practical applications.

Updated

Declare a singleton with object and access its members through its name:

object Logger {
  def format(message: String): String = s"Log: $message"
  def log(message: String): Unit = println(format(message))
}
class Service {
  object Identity
}
@main def singletonExample(): Unit = {
  assert(Logger.format("Started") == "Log: Started")
  val alias = Logger
  assert(alias eq Logger)
  val first = new Service
  val second = new Service
  assert(!(first.Identity eq second.Identity))
}

An object defines a single instance associated with that declaration's enclosing scope. A member object is associated with each enclosing instance, as shown; it is not a global singleton shared by all Service instances. On the JVM, class-loader boundaries also matter for top-level objects. Singleton objects

Objects are useful for stateless utilities, named values and companions to classes. They do not automatically serialize method calls or make mutable fields, connection pools or external clients thread-safe. Shared resources still need appropriate synchronization, configuration and cleanup. Keep initialization controlled and avoid hiding resource ownership inside an object merely to avoid passing a dependency.

Related Questions