Home »
Scala language
Scala singleton and companion objects
Scala is an object-oriented programming language, that defines singleton and companion objects to make it's functioning easy. In this tutorial, we will learn about singleton and companion objects in Scala with working examples.
Submitted by Shivang Yadav, on September 05, 2019
Singleton objects in Scala
Scala being an object-oriented programming language has the capability to create an object that can define its members without a class.
A singleton Object has no class associated with it i.e. It exists without any class. It is defined using the object keyword not the class keyword and is an instance, not a blueprint hence it does not require an external call to execute its methods.
Why Singleton Object?
Every program needs a point from where the execution starts. In OOPS classes need objects to get executed. But the main() method needs to be executed first to call other members of the class.
For executing the main() method in scala many object-oriented programming languages use the static keyword but it scala programming language there is no static keyword. That is why in scala we use a singleton object that defines the main method.
Singleton objects
An object that can exist without a class is a singleton object. It objects keyword is used to define it.
Syntax:
object singleton_objname {
// object code , member functions and fields.
}
Features of singleton object
Program to show implementation of singleton object
object findsum{
var a = 56
var b = 21
def sum(): Int ={
return a+b;
}
}
object Main
{
def print(){
printf("The sum is : "+ findsum.sum());
}
def main(args: Array[String])
{
print();
}
}
Output
The sum is : 77
Explanation:
This program is to illustrate the use of singleton objects in Scala. The program is to find the sum of given numbers and return it. There are 2 objects findsum and Main. The findsum object calculates the sum of the two numbers with the sum method. And the Main object has two methods print() and main(). The print method, prints the value that is returned by sum() method.
Companion object in Scala
If a class and a singleton object have the same name. Then, the class is called a companion class and singleton object is called a singleton object.
Both the class and object are defined in the same program file.
Program to show implementation of companion object
class companion{
var a = 23;
var b = 78;
def sum(){
println("The sum is: "+ (a+b));
}
}
object companion{
def main(args:Array[String]){
new companion().sum();
}
}
Output
The sum is: 101
Explanation:
This program is to illustrate the concept of a companion object. Here, the program is used to find the sum of the given integer. To calculate the sum we have a method sum in companion class. We will call this method from the companion object using the dot operator.