0

我认为一旦通过伴生对象创建了该类的对象,我就可以调用该类的方法。但我无法做到这一点。下面是我的代码:

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?
}

朋友们,你能帮我理解它为什么会这样吗?谢谢。

4

1 回答 1

2

我知道了!!。问题在于:

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

我错过了等号,这就是为什么我错过了对象链接,即使它正在创建。现在更改代码是:

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

它现在工作得很好。谢谢。

于 2013-09-09T11:36:05.993 回答