object keyword in scala



The object keyword in scala creates a new singleton type, similar to the singleton class in Java i.e. its instance cannot be created twice and only has a single named instance. It's just like creating a new instance of the anonymous class in Java. Scala doesn't have a static concept. So scala creates a singleton object to provide an entry point for your program execution. If you don't create a singleton object, your code will compile successfully but will not produce any output. Methods declared inside Singleton Object are accessible globally. A singleton object can extend classes and traits.

object Singleton{  
    def main(args:Array[String]){
        //no object creation is needed here  
        SingletonObject.hello()
    }  

object SingletonObject{  
    def hello(){  
        println("Hello, This is Singleton Object")  
    }  

} 

Output:
Hello, This is Singleton Object


In scala, when we have a class with the same name as a singleton object, it is called as a companion class and the singleton object is called a companion object.
These companion class and companion object should always be in the same file.

Scala Companion Object Example

class ComapanionClass{  
    def hello(){  
        println("Hello, this is Companion Class.")  
    }  
}  

object CompanoinObject{  
    def main(args:Array[String]){  
        new ComapanionClass().hello()  
        println("And this is Companion Object.")  
    }  
} 

Output:
Hello, this is Companion Class.
And this is Companion Object.

Comments

Popular posts from this blog

Functional Programming in Java - Part 1

Communication between two Actor's In scala

Stopping the Actor in Akka