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.
I got it!!. The problem was in the line:
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:
It is working perfectly fine now. Thanks.