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...