Scala 中伴随对象属性的初始化

Companion Object Attributes Initialization in Scala

嗨,我无法理解以下程序中的一件事。 当我创建一个新客户时,我会得到增加的帐号。 为什么我的账号总是不是1002?

class Customer {
  private var Name: String = _
  private var AccountBalance: Int = _
  private var AccountNumber: Int = _

  def this(name: String, accountbal: Int) {
    this()
    this.Name = name
    this.AccountBalance = accountbal
    this.AccountNumber = Customer.generateAccountNumber()
  }

  def displayDetails() {
    println(s"Customer Account number is $AccountNumber \nCustomer Name is $Name \nAccount Balance is $AccountBalance")
  }
}

object Customer {
  var accountNumber = 1001

  def generateAccountNumber(): Int = {
    accountNumber += 1; accountNumber
  }
}

理解的关键是只有一个 单个 伴随对象实例,它在 class 的不同实例之间共享,例如

class A {
  A.x += 1
}
object A {
  var x = 0
}

new A
new A
new A
A.x
// val res3: Int = 3

此处 class A 的每个实例化都会在同一伴随对象 A.

中递增相同的可变状态 x