class Account {
val id = Account.newUniqueNumber()
private var balance = 0.0
def deposit(amount: Double) { balance += amount }
}
object Account {
private var lastNumber = 0
private def newUniqueNumber() {
lastNumber += 1; lastNumber
}
}
var a1 = new Account()
var a2 = new Account()
println(a1.id)
println(a2.id)
~/myScala % scala -version
Scala code runner version 2.9.1 -- Copyright 2002-2011, LAMP/EPFL
~/myScala % scala Account.scala
()
()
~/myScala %
我期待 1,2 作为输出...我的推理是...
1. 构造了一个新的 Account 对象
2. 在初始化 id 字段时,构造了伴随对象(仅一次)
所以 newUniqueNumber() 调用应该返回 1 和 2...
任何指针?
谢谢..