Updated April 14, 2023
Definition of Scala singleton
Scala language is an object oriented programming language hence it support the singleton object concept. But in java, they provide us static keyword for this. Singleton objects are more powerful concept came in. As the name it allows us to create only one object of a class that means we define only a single object for a class. In scala, singleton objects are the entry point of our program. So if we do not define a singleton object for our class compilation will fail.
Syntax:
object USER_DEFINED_NAME{
// write logic here
}
Here we use the object keyword to create our singleton object. Inside this, we can write our logic. Let’s take a look below;
object Demo {
def m1(message: String){
println("singleton method called.")
}
}
In the above syntax, we are using the object keyword to define our singleton object. Also, we can use this m1 () method anywhere by importing this class package. In singleton classes, we can define our utility method which can be used anywhere in the code to reduce the redundant code.
How does Singleton Object Work in Scala?
Singleton object works in the same way like static keyword in java. Singleton object means only one instance of the class not multiple. In java, we can access the static method by the name of the class but here in scala we just need to import the class package containing the method and we can us it directly. Singleton objects are lazy created objects as they have exactly only one instance of the class. In scala at the root level, the class object is a singleton.
Like;
package Demopck
object Demo {
def m1(message: String){
println("message is ::" +message)
}
}
import Demopck.Demo.m1
class Employee(name: String, id: Int)
class Test {
val emp1 = new Employee("ABC XYZ", 001)
val emp2 = new Employee("IOP YHG", 005)
val emp3 = new Employee("TYH PPP", 006)
val emp4 = new Employee("OIU DFR", 007)
m1("called singleton object method.")
}
In the above example what we are doing is we made one singleton object. Also, we make one employee class to test our changes. This m1() method can be used as a utility method in any class just by importing the changes. In the test class, we have import the Demo class and method m1() at the end of the code we are calling our method directly without any class reference. That means the object of the class got created at the beginning only and we are referring to the same object to refer the method.
We can call the singleton object method by two ways;
1. By directly referring the class name followed by the method name that we want to call. In both the ways we do not need to create the object for the class we just need to refer the method by the class name append before the method.
eg: class_name.Method_name()
2. By importing the class which contains the method
eg: import packagename.classname.methodname
Points to be remembered while working with the singleton Scala objects;
- In scala language, the main method is always present inside a singleton object because the flow of the program initiates from there only.
- Our singleton object would be accessible globally in our application.
- In scala, we can extend traits and class inside singleton classes.
- We can create an instance of the singleton class. As it gets created only once.
- We cannot pass parameters inside the constructor of the singleton class.
- No need to create the object of the singleton class to access their method because they can directly be accessed via class name only.
Examples of Scala Singleton
Following are the examples as given below:
Example #1
In this example, we are calling the singleton method from the main method.
Code:
object Main extends App{
// Your code here!
//defining singleton object
object Demo {
def m1(message: String): Unit = println(s"INFO: $message")
}
val emp1 = new Employee("TABC", 001)
val emp2 = new Employee("TTYUs",002)
val emp3 = new Employee("TOPO", 003)
// calling siglenton method via class name.
Demo.m1("calling singleton method ")
}
class Employee(name: String, id: Int)
Output:
Example #2
In this, we are calculating the area of the rectangle.
Code:
object Main extends App{
// Your code here!
var result = new Rectangle();
result.area() ;
}
class Rectangle
{
var l = 20;
var h = 40;
// Method which gives the area of the rectangle
defarea()
{
var area = l * h;
println("Length rectangle is:" + l);
println("Height rectangle is:" + h);
println("Area rectangle is :" + area);
}
}
Output:
Example #3
In this example, we are printing our message by calling the method from singleton class.
Code:
object Main extends App{
// Your code here!
//we are calling the methood from main
SingletonDemo.show()
}
object SingletonDemo
{
// Varaibles of singleton object
var message1 = "Hello to all from singleton";
var message2 = "Message to be priented";
// Method of singleton object
defshow()
{
println("string one is :: "+ message1);
println("string second is :: "+ message2);
}
}
Output:
Example #4
In this example, we are passing some parameters to test the input and output through singleton objects.
Code:
object Main extends App{
// Your code here!
//we are calling the methood from main
DrawDemo.test(1)
DrawDemo.test(2)
DrawDemo.test(10)
}
object DrawDemo
{
// Varaibles of singleton object
var draw1 = "This is one drwaing";
var draw2 = "This is second";
// Method of singleton object
deftest(num: Int)
{
if(num == 1){
println("draw 1 message is :: " + draw1)
}
if(num == 2){
println("draw 2 message is :: " + draw1)
}
if(num != 1 || num != 2){
println("nothing match !!!!")
}
}
}
Output:
Conclusion
Scala singleton object used when only one instance of the class is needed. It also helps us to maintain the utility method for our application which is used at many places. Thus reducing the redundancy of the code as well. Also, we can extend traits and classes as well by using singleton objects. They are important because they provide entry for the program execution.
Recommended Articles
We hope that this EDUCBA information on “Scala Singleton” was beneficial to you. You can view EDUCBA’s recommended articles for more information.