Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala
classes

What are Singleton Objects in Scala?

Dian Us Suqlain

Scala if compared to Java is more Object-Oriented. There’s no concept of the static keyword in Scala instead, we have singleton objects.

Singleton Object is an object which has one and only one instance which is used in the entire program.

Singleton class diagram

Code

object Name{
  // code...
}

Example

object SingletonExample{
    // Variable of singleton object
    var obj1 = "This is a Singleton Object"
     
    // Method of singleton object
    def show(): Unit =  {
        println(obj1)
    }
}
 
// Singleton object with named as Main
object Main
{
    def main(args: Array[String]): Unit =  {
        // Calling method of singleton object
        SingletonExample.show()
    }
}
Scala Singleton Object

In the above example, we have a Singleton Object, i.e.,

  • SingletonExample
  • Main

SingletonExample contains a method named show(). Now, we call this method in Main Object.

Using the statement SingletonExample.show(), we call show() method that is present in SingletonExample object and print output.

Some key points regarding Singleton Objects

  • The method inside Singleton Object is globally accessible

  • The main method should always be present in Singleton Object

  • No need to create an object to access the method of Singleton Object

RELATED TAGS

scala
classes

CONTRIBUTOR

Dian Us Suqlain
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring