1.

What Is A Companion Object In Scala? What Is A Companion Class In Scala? What Is The Use Of Companion Object In Scala?

Answer»

In simple words, if a Scala class and object shares the same name and defined in the same source file, then that class is known as “Companion Class” and that object is known as “Companion Object”.

When we CREATE a Class by using Scala “class” keyword and Object by using Scala “object” keyword with same name and within the same source file, then that class is known as “Companion Class” and that object is known as “Companion Object”.

Example:-

Employee.scala
class Employee{ }
object Employee{ }

In Scala, The MAIN PURPOSE of Companion Object is to define apply methods and avoid using new keyword in CREATING an instance of that Companion class object.

In simple words, if a Scala class and object shares the same name and defined in the same source file, then that class is known as “Companion Class” and that object is known as “Companion Object”.

When we create a Class by using Scala “class” keyword and Object by using Scala “object” keyword with same name and within the same source file, then that class is known as “Companion Class” and that object is known as “Companion Object”.

Example:-

Employee.scala
class Employee{ }
object Employee{ }

In Scala, The main purpose of Companion Object is to define apply methods and avoid using new keyword in creating an instance of that Companion class object.



Discussion

No Comment Found