Companion Objects in Scala

Mohammad Irfan Apr 21, 2022
Companion Objects in Scala

This tutorial will discuss the companion objects with running examples in Scala.

Companion Objects in Scala

A companion object is an object with the same name as the class and is declared in a similar file as a class.

For example, if we have a Color object with the same name as the class name and the file is saved as Color.scala, this object will be considered a companion object in Scala.

Example:

class Color {
}
object Color {
}
// Color.scala

The benefit of using a companion object is that both the class and the object can now access each other’s private members. Scala does not use the static concept, but we can use the companion objects to collect for a similar concept.

Create Objects Without Using the new Keyword

Adding an apply() method to a companion object allows us to create objects without using the new keyword.

Example:

class Color(val name: String){
    private  var _defaultname: String = "White"
     def get():String = _defaultname
}

object Color {
  def apply(name: String): Color = new Color(name)
}

object MyClass {

    def main(args: Array[String]) {
        val color = Color("Red")
        println(color.name)
    }
}

Output:

Red

Deconstruct the Instance of a Class

Similarly, we can use the unapply() method to deconstruct the instance of the class. We obtain an error if we try to access its members after the unapply() function.

Example:

class Color(val name: String){
    private  var _defaultname: String = "White"
     def get():String = _defaultname
}

object Color { // unapply function
  def unapply(name: String): Color = new Color(name)
}

object MyClass {

    def main(args: Array[String]) {
        val color = Color("Red")
        println(color.name)
    }
}

Output:

error: Color.type does not take parameters
        val color = Color("Red")
                         ^

Related Article - Scala Object