Thursday 17 September 2020

How to define static methods and singletons

 Scala deals with singleton and static methods different way. If you want to define static methods or variables, define them in an object construct.

 

Syntax

object ClassName{

 

}

 

Example

object Employee {
     val ORGANIZATION_NAME = "ABC Corp"

      def getOrg(): String = {
          ORGANIZATION_NAME
     }
}

 

You can call the method getOrg using Employee (no need of an instance)

 

Employee.getOrg()

scala> object Employee {
     |      val ORGANIZATION_NAME = "ABC Corp"
     | 
     |       def getOrg(): String = {
     |           ORGANIZATION_NAME
     |      }
     | }
     | 
object Employee

scala> 

scala> Employee.getOrg()
val res1: String = ABC Corp

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment