Scala Singleton Object and Companion Object

Singleton Object

There is no static concept in Scala.A Singleton Object is a class that has exactly one instance. It is created lazily when it is referenced, like a lazy val.

Methods declared inside Singleton Object are accessible globally. A singleton object can extend classes and traits.

package com.scala.test

object TestSingleton {
def testMethod() {
println(“This is test method”)
}
}

object Singleton1 {
def main(args: Array[String]) {
TestSingleton.testMethod()
}
}

Output
This is test method

Companion Object

A companion object is an object with the same name as a class or trait and is defined in the same source file as the associated file or trait. A companion object differs from other objects as it has access rights to the class/trait that other objects do not. In particular it can access methods and fields that are private in the class/trait.

package com.scala.test

class TestCompanion {
private val name = “Gyan” //private field
}

object TestCompanion {
def printName = {
val test = new TestCompanion
println(test.name)// Access private field
}
def main(args: Array[String]) {
TestCompanion.printName
}
}

Output
Gyan

Leave a Reply

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