Thursday, 17 September 2020

Scala: Companion Object

 Companion object has exactly same name as the class name and defined in the same source file. In Scala, both companion object and companion class can access each other private features.

 

How to define companion object for the class Employee?

Since both companion object and companion class should be defined in same file, open scala prompt and execute the command :paste. ‘:paste’ command opens an editor, paste below snippet.

class Employee(id: Int, firstName: String, lastName: String) {

  override def toString() = {
    s"$id, $firstName, $lastName"
  }

}

object Employee {
  def getEmployee(): Employee = new Employee(0, "no_name", "no_name")

  def getEmployee(id: Int): Employee = new Employee(id, "no_name", "no_name")

  def getEmployee(id: Int, firstName: String, lastName: String): Employee = new Employee(id, firstName, lastName)

}


scala> :paste
// Entering paste mode (ctrl-D to finish)

  class Employee(id: Int, firstName: String, lastName: String) {

    override def toString() = {
      s"$id, $firstName, $lastName"
    }
    
  }

  object Employee {
    def getEmployee(): Employee = new Employee(0, "no_name", "no_name")

    def getEmployee(id: Int): Employee = new Employee(id, "no_name", "no_name")

    def getEmployee(id: Int, firstName: String, lastName: String): Employee = new Employee(id, firstName, lastName)

  }


// Exiting paste mode, now interpreting.

class Employee
object Employee

 

Now you can use the method 'getEmployee' defined in companion object to define new Employee instances.

 

val emp1 = Employee.getEmployee()

val emp2 = Employee.getEmployee(10)

val emp3 = Employee.getEmployee(10, "Krishna", "Gurram")

scala> val emp1 = Employee.getEmployee()
val emp1: Employee = 0, no_name, no_name

scala> val emp2 = Employee.getEmployee(10)
val emp2: Employee = 10, no_name, no_name

scala> val emp3 = Employee.getEmployee(10, "Krishna", "Gurram")
val emp3: Employee = 10, Krishna, Gurram

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment