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.
object Name{
// code...
}
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() } }
In the above example, we have a Singleton Object, i.e.,
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.
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
CONTRIBUTOR
View all Courses