Scala

Scala Companion Object Explained

What is a companion object?

  • Companion object is nothing but a singleton object which will have same name as the class name and it will hold all the static methods and members.
  • Since, Scala doesn’t support definition of static methods in the class we have to create the companion object.
  • Both the class and companion object should need to have same name and should be present in the same source file.

companion object explained 24tutorialsConsider the below example –

class ListToString private(list: List[Any]) {

  def size(): Int = {
    list.length
  }

  def makeString(sep: String = ","): String = {
    list.mkString(sep)
  }

}

object ListToString {
  def makeString(list: List[Any], sep: String = ","): String = {
    list.mkString(sep)
  }

  def apply(list: List[Any]): ListToString = new ListToString(list)
}

Class ListToString defined with two methods. Those methods can only be accessible when a object is instantiated for the class.

But the methods which is defined in the ListToString singleton object can be accessible globally and no need to create new ListToString object for the methods defined in the ListToString singleton object.

We can use :paste mode in the scala shell to create Companion object-

Lets declare a list which contains list of integers.

scala> val list: List[Int] = List(1,2,3,4,5)
list: List[Int] = List(1, 2, 3, 4, 5)

Create an object using ListOfString class using above list.

scala> val list_to_string = ListToString(list)
list_to_string: ListToString = ListToString@2ae2fa13
scala> list_to_string.size
res0: Int = 5
scala> list_to_string.makeString("~")
res1: String = 1~2~3~4~5

Here, we haven’t used new keyword this can be done by defining apply method in the companion object and if we set the constructor of the companion class to private user will not be able to use the new keyword while instantiating the new object.We have used the instance methods to do some operations on the object.

scala> import ListToString.makeString
import ListToString.makeString
scala> makeString(list, "~")
res2: String = 1~2~3~4~5

But now, we have imported makeString method from the singleton object and then we are calling that method with arguments without instantiating a new object.

Why we need a companion?

  • Separation of concerns using companion. i.e. separation of static and non-static methods.
  • Implementation of factory methods and builder pattern.

Share This Post

He is an Enthusiastic, Music Lover, Gadget Freek. He loves to learn and explore new technologies. He is an Software Developer with hands on experience in Hadoop, Scala, Spark, Shell Scripting, Hive and Oracle PL-SQL.

Lost Password

Register

24 Tutorials