As we know, Scala is a pure object-oriented language because every value is an object in Scala. Instead of static members, Scala offers singleton objects. A singleton is nothing but a class that can have only one instance.
In this type of class, you need not create an object to call methods declared inside a singleton object. Instead, the method in the singleton object is accessed with the object's name (just like calling a static method in Java). In Scala, the main method is always present in a singleton object. A singleton object can extend class and traits.
Creating singleton objects using an object keyword instead of a class keyword is possible.
Example:
Output:
In Scala, an object is a class with exactly one instance created lazily when we reference the object. The methods declared inside the Scala singleton object are globally accessible; we don’t need an object for this. We can import them from anywhere in the program.
And since Scala has no idea of static’, we must provide a point of entry for the program to execute. Scala singleton object makes for this. Without such an object, the code compiles but produces no output.
Another example:
Output: