Thursday, 28 January 2016

Scala Singleton And Companion Objects

Scala classes cannot have static variables or methods. Instead a Scala class can have what is called a singleton object, or sometime a companion object.

A singleton object is declared using the object keyword. Here is an example:



object MainObject {
    def sayHello() {
        println("Hello Krishna Kumar Chourasiya!");
    }
}
 
 
This example defines a singleton object called MainObject. You can call the method sayHello() like this: 

MainObject.sayHello();

Notice, how you write the full name of the object before the method name. No object is instantiated. It is like calling a static method in Java, except you are calling the method on a singleton object instead.

Companion Objects

 When a singleton object is named the same as a class, it is called a companion object. A companion object must be defined inside the same source file as the class. Here is an example:

class MainClass {
    def sayHello() {
        println("Hello! Krishna Kumar Chourasiya");
    }
}

object MainClass {
    def sayHi() {
        println("Hi! Krishna Kumar Chourasiya");
    }
}

In this class you can both instantiate Mainlass and call sayHello() or call the sayHi() method on the companion object directly, like this:

var aMainObj : MainClass = new MainClass();
aMainObj.sayHello();    // print - Hello! Krishna Kumar Chourasiya

MainClass.sayHi();    // print - Hi! Krishna Kumar Chourasiya



 3 Cheers !!!







No comments:

Post a Comment

Monads in Scala

Monads belongs to Advance Scala   concepts. It  is not a class or a trait; it is a concept. It is an object which covers other object. A Mon...