![]() |
VOOZH | about |
Scala is more object oriented language than Java so, Scala does not contain any concept of static keyword. Instead of static keyword Scala has singleton object. A Singleton object is an object which defines a single object of a class. A singleton object provides an entry point to your program execution. If you do not create a singleton object in your program, then your code compile successfully but does not give output. So you required a singleton object to get the output of your program. A singleton object is created by using object keyword.
Syntax:
object Name{
// code...
}
Important points about singleton object
Example 1:
Output:
Height of the rectangle is:40 Length of the rectangle is:20 Area of the rectangle is :800
Example 2:
Output:
Welcome ! GeeksforGeeks This is Scala language tutorial
Explanation: In the above example, we have two singleton objects, i.e, Exampleofsingleton and Main. Exampleofsingleton object contains a method named as display(), now we call this method in Main object. Using this statement Exampleofsingleton.display(); we call display() method that is present in Exampleofsingleton object and print output.
Companion object is known as an object whose name is same as the name of the class. Or In other words, when an object and a class have the same name, then that object is known as the companion object and the class is known as companion class. A companion object is defined in the same source file in which the class is defined. A companion object is allowed to access both private methods and private fields of the class.
Example:
Output:
GeeksforGeeks Tutorial of Companion object