What are Companion object and Singleton object in Scala?

Singleton Object

Singleton objects are the objects that are defined using the keyword object before it and we don't need to create any instance to call the methods that are defined in it. In Scala all the objects except companion objects are singleton. Methods declared in inside Scala objects can be accessed globally and we don't need to create any objects to access them. We can import them from anywhere in our program. As Scala language doesn't have concept called "static", there should be a point of entry foe the program to execute. Using Scala singleton object we can achieve this. Singleton objects can extend traits and classes.

Code:

package com.bigdatainterview.questions
//com.bigdatainterview.questions.SingletonDemo
object SingletonDemo {
def main(args:Array[String])={
SingletonObject.printMessage()
}
}

object SingletonObject{
def printMessage():Unit = {
println("Singleton object's method called without creating it's object")
}
}

Output:

Singleton object's method called without creating it's object

Scala Companion Object

A companion is an object that has exact name as a class. Then we will it as companion object of that class. Companion object and it's class must be  in same source code file. Both class and it's companion object can access the other's private variables.

Code:

object CompanionObjectDemo {
def main(args: Array[String]):Unit = {
val compObj = new CompanionObjectDemo()
compObj.companionObjectMethod
compObj.privateMethod
}
}

class CompanionObjectDemo{
def companionObjectMethod():Unit = {
println("Companion object's method called")
}
private def privateMethod():Unit = {
println("Even private methods can be accessed using compnion object")
}
}

Output

Companion object's method called
Even private methods can be accessed using compnion object

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *