Google News
logo
Scala - Interview Questions
What is the advantage of companion objects in Scala?
Classes in the Scala programming language do not have static methods or variables, but instead, they have what is known as a Singleton object or Companion object. The companion objects, in turn, are compiled into classes with static methods.

A singleton object in Scala is declared using the keyword object as shown below :
object Main {
def sayHello () {
println ("Hello!");
 }
}​

In the above code snippet, Main is a singleton object, and the method sayHello can be invoked using the following line of code
Main. SayHello ();​
If a singleton object has the same name as the class, then it is known as a Companion object and should be defined in the same source file as that of the class.
class Main {
def sayHelloWorld() {
println("Hello World");
 }
}

object Main {
def sayHello() {
println("Hello!");
 }
}​

Advantages of Companion Objects in Scala :

* Companion objects are beneficial for encapsulating things and act as a bridge for writing functional and object-oriented programming code.

* The Scala programming code can be kept more concise using companion objects, as the static keyword need not be added to every attribute.

* Companion objects provide a clear separation between static and non-static methods in a class because everything that is located inside a companion object is not a part of the class’s runtime objects but is available from a static context and vice versa.
Advertisement