What is Singleton object in Scala?

What is Singleton object?

Scala doesn't have a concept called static. Instead of static, scala has something called Singleton object. A singleton object is an object that defines only one instance of a class. Normally this singleton object provides entry point any program we write in Scala. Without this singleton object we can compile a Scala program but we cannot get output of it. Singleton object will be defined with a preceding keyword object before the object name.

Syntax:

object Name{
// code...
}

 

Properties of Singleton object:

  • The method in the singleton object is globally accessible.
  • You are not allowed to create an instance of singleton object.
  • You are not allowed to pass parameter in the primary constructor of singleton object.
  • In Scala, a singleton object can extend class and traits.
  • In Scala, a main method is always present in singleton object.
  • The method in the singleton object is accessed with the name of the object(just like calling static method in Java), so there is no need to create an object to access this method.

Leave a Reply

Your email address will not be published. Required fields are marked *