WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Scala · Intermediate · question 29 of 100

What are the different ways to create and use Singletons in Scala?

📕 Buy this interview preparation book: 100 Scala questions & answers — PDF + EPUB for $5

Singletons are objects that can have only a single instance throughout the lifetime of a program. Singleton pattern ensures that a class provides only one instance with global access to that instance. Scala provides different ways to create and use Singletons. Let’s discuss four methods:

1. Object: The most straightforward way to create Singleton patterns in Scala is by using ‘object‘. An object in Scala is a class with a single instance. When the object is declared, Scala automatically creates an instance and makes it globally accessible. Here is an example:

object Singleton {
  def greet(): Unit = {
    println("Hello, I am a Singleton!")
  }
}

// Usage
Singleton.greet()

2. Class and Companion Object: Using companion objects is another way of creating Singletons. Create a class that holds the logic but restricts the direct construction of an instance via ‘private constructor‘. Then define a companion object for the class that holds the single instance and provides a global access point.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Scala interview — then scores it.
📞 Practice Scala — free 15 min
📕 Buy this interview preparation book: 100 Scala questions & answers — PDF + EPUB for $5

All 100 Scala questions · All topics