我认为一旦通过伴侣对象创建了该类的对象,我就可以调用类的方法。但我无法做到这一点。 以下是我的代码:
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?
}
朋友们,你能帮我理解为什么会这样吗?感谢。
答案 0 :(得分:2)
我明白了!!问题在于:
def apply(initialBalance: Int) {
new Employee(newUniqueId, initialBalance)
}
我错过了等号,这就是为什么我错过了对象链接,即使它已经被创建了。现在更改代码是:
def apply(initialBalance: Int) = {
new Employee(newUniqueId, initialBalance)
}
现在工作得非常好。感谢。