Updated April 14, 2023
Introduction to Scala Companion Object
Scala companion are the objects in the Scala file which has the same name as that of class. It can access private members. They have static methods that are compiled to classes. An object with the same name as class name in Scala and is declared in the same file as the class those are known to be as Scala Companion and the class is known as Companion class.
They are a good encapsulator of code and act as the bridge for functional and object-oriented code. Companion objects provides a clear picture between static and nonstatic methods inside code.
Syntax:
// SCALA CODE :-
Class Class_Name
{
//class methods and body
}
Object Class_Name
{
// Object Body
}
How Does Companion Object work?
Scala companion objects allow us the create an instance of classes without using the new keyword. There is a factory method apply in the companion objects that let us call the object without using the new keyword. It is just like a syntactic sugar in Scala that turns the code with the apply method during compilation.
A benefit of having a companion object is that we can access their private members.
Example #1
Code:
class Animal {
var a = ""
}
object Animal {
defapply(a: String): Animal = {
var p = new Animal
p.a = a
p
}
}
defined class Animal
defined object Animal
scala>val d = Animal("DOg")
d: Animal = Animal@4748a0f9
scala>val e = Animal.apply("Dog")
e: Animal = Animal@6548bb7d
Output:
Here we see that with the help of companion objects we are able to call the method directly.
This apply method can have more than one argument and the companion object can have more than one apply the method to provide multiple constructors.
Example #2
Code:
class Animal {
var a = ""
var b = ""
}
object Animal {
defapply(a: String): Animal = {
var p = new Animal
p.a = a
p
}
defapply(a: String, b: String): Animal = {
var p = new Animal
p.a = a
p.b = b
p
}
}
scala> val e = Animal("Dog","5")
e: Animal = Animal@512d4583
scala>val f = Animal.apply("Dog","5")
f: Animal = Animal@4d8126f
Output:
Method Unapply of Scala Companion Object
Here we saw that adding apply method lets us create new objects, in the same way, we can use UNAPPLY method to the de-construct instance.
Applying the unapply method in the companion object creates an extractor method to extract the field out of objects. The unapply method enables a convenient form of pattern matching in the match expression.
Example #1
Code:
class Animal {
var a = ""
var b = ""
}
object Animal {
defapply(a: String): Animal = {
var p = new Animal
p.a = a
p
}
defapply(a: String, b: String): Animal = {
var p = new Animal
p.a = a
p.b = b
p
}
defunapply(p: Animal): String = s"${p.a}, ${p.b}"
}
scala>val d = Animal("Dog","5")
d: Animal = Animal@4e52d2f2
scala>val r = Animal.unapply(d)
r: String = Dog, 5
Output:
Here we can see that method unapply deconstructs the object instance into its individual components.
This companion objects have a great role in scala pattern matching as the method unapply takes an object and outputs the argument.
Example #2
Code:
object Animal {
defapply(a: String) = s"$a"
defunapply(Animal: String): Option[String] = {
valsd: Array[String] = Animal.split("")
if (sd.tail.nonEmpty) Some(sd.head) else None
}
}
vald = Animal("Dog")
d match {
case Animal(a) =>println(a)
case _ =>println("Not Found Animal")
}
Output:
So here in the above piece of code, we are using both the methods apply and unapply for creating and pattern matching in the Animal Class.
Here the object apply method is used to create it from the name of the animal whereas the unapply method is used to inverse it. So while calling inside a case class we are calling the unapply method above and a normal calling of the object will call the apply method.
So with the help of this particular method, we are able to write the pattern matching codes in scala.
vala = Animal("Dog")
calling the apply method
Animal.apply(“Dog”)
Calling the unapply method used for pattern matching.
a match {
case Animal(a) =>println(a)
Animal.unapply(“Dog”)
So in this way, we can have the use of scala companion objects in our Scala code and make the object calling part easier.
Conclusion
Here from the above article, we had a fairer idea about the Scala Companion objects and we checked how it helps in Scala Applications. We checked how to apply method is used for companion object and used to call the object without the use of the new operator. With the several examples, we saw how to apply and unapply method works on the companion objects.
So this is a very interesting concept of SCALA that gives us a clear picture of the object creation.
Recommended Articles
This is a guide to Scala Companion Object. Here we discuss a brief overview of Scala Companion Object and its different examples along with code Implementation. You can also go through our other suggested articles to learn more –