top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the advantage of companion objects in Scala?

+1 vote
620 views
What is the advantage of companion objects in Scala?
posted Nov 9, 2016 by Shyam

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Classes in Scala programming language do not have static methods or variables but rather they have what is known as a Singleton object or Companion object. The companion objects in turn are compiled to classes which have 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 that of the class then it is known as a Companion object and it 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 they act as a bridge for writing functional and object oriented programming code.
Using companion objects, the Scala programming code can be kept more concise as the static keyword need not be added to each and 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.

answer Nov 11, 2016 by Karthick.c
...