Override toString method is not getting called from Companion Object

427 views Asked by At

I thought I can call methods of class once I created the object of that class through companion object. But I am not able to do that. Below is my code:

class Employee(val id: Int, val initialBalance: Int) {
  val message = println("Object created with Id: " + id + " balance: " + initialBalance)

  def printEmployeeDetails = "Id: " + id + " InitialBalance: " + initialBalance
  override def toString = "Id: " + id + " InitialBalance: " + initialBalance
}

object Employee {
  private var id = 0

  def apply(initialBalance: Int) {
    new Employee(newUniqueId, initialBalance)
  }

  def newUniqueId() = {
    id += 1
    id
  }

}

object testEmployee extends App {
  val employee1 = Employee(100)
  employee1.printEmployeeDetails  //getting error, why?
  println(employee1)    // This line is printing (), why?
  val employee2 = Employee(200)
  println(employee2)    // This line is printing (), why?
}

Friends, can you help me to understand why it is behaving like this? Thanks.

1

There are 1 answers

0
Sudipta Deb On

I got it!!. The problem was in the line:

def apply(initialBalance: Int) {
    new Employee(newUniqueId, initialBalance)
}

I missed the equal sign and that is why I was missing the object link even though it was getting created. Now the change code is:

def apply(initialBalance: Int) = {
    new Employee(newUniqueId, initialBalance)
}

It is working perfectly fine now. Thanks.