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.


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

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


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.


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

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")


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 *