Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the responsive-lightbox domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114

Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the hueman domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114
Scala - Singleton Object - Testingpool

Scala – Singleton Object

In this tutorial, we are going to learn what is Singleton Object in Scala. You would be aware of static keyword in java which belongs to the class. One way in which Scala is more object-oriented than Java is that classes in Scala cannot have static members. Instead, scala uses Singleton Object. Singleton object is defined similar to class definition, except that we use Object keyword instead of Class keyword.

The methods, variable declared inside scala singleton object are globally accessible. We don’t need to create an object from class. We can directly call methods declared inside singleton object.

package main.testingpool

object Mobile {   
  def model: Unit ={
    println("Phone model: ")
  }
}

object Iphone extends App{
   Mobile.model   // No need to create object. Direct method call
}
Output - Phone model: 

Because the method model is defined in an object instead of a class, it can be called in the same way as a static method in Java. A singleton object can extend classes and traits.

Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...