Singleton Objects

    As we know, Scala is a pure object-oriented language because every value is an object in Scala. Instead of static members, Scala offers singleton objects. A singleton is nothing but a class that can have only one instance.

    In this type of class, you need not create an object to call methods declared inside a singleton object. Instead, the method in the singleton object is accessed with the object's name (just like calling a static method in Java). In Scala, the main method is always present in a singleton object. A singleton object can extend class and traits.

    Creating singleton objects using an object keyword instead of a class keyword is possible.


    object ConfigReader {                                        // Singleton object created using 
      object keyword
      def getUserDetail() = "TGB USER"
      def getPassword(user: String = "TGB USER") = "PASSWORD_FROM_DB"
    val usr = ConfigReader.getUserDetail()            // Object creation not needed to call method
    val pwd = ConfigReader.getPassword()


    val usr: String = TGB USER
    val pwd: String = PASSWORD_FROM_DB

    In Scala, an object is a class with exactly one instance created lazily when we reference the object. The methods declared inside the Scala singleton object are globally accessible; we don’t need an object for this. We can import them from anywhere in the program.

    And since Scala has no idea of static’, we must provide a point of entry for the program to execute. Scala singleton object makes for this. Without such an object, the code compiles but produces no output.

    Another example:

    import java.util.logging.{Level, Logger}
    object LoggerFactory {
      val logger = Logger.getLogger("MyLogger")
      def info(message: String) =
      def error(message: String) = logger.log(Level.SEVERE, message)
      def warn(message: String) = logger.warning(message)
    LoggerFactory.error("Failed to start")"This is logger example")
    LoggerFactory.warn("Hey! you used a singleton object")


    Jul 21, 2022 9:07:50 AM $line20.$read$$iw$LoggerFactory$ error
    SEVERE: Failed to start
    Jul 21, 2022 9:07:54 AM $line20.$read$$iw$LoggerFactory$ info
    INFO: This is logger example
    Jul 21, 2022 9:07:54 AM $line20.$read$$iw$LoggerFactory$ warn
    WARNING: Hey! you used a singleton object