谁能给我一个关于"What makes an object stateful"这种情况的好例子?

Can anyone give me a good example of This kind of situation about "What makes an object stateful"?

我不明白这句话的意思(来自Scala-Threading/Odersky/18-stateful-objects.txt line 88):

a class might be stateful without defining or inheriting any vars because it forwards method calls to other objects that have mutable state.

任何人都可以给我一个 Scala 中这种情况的好例子吗?

class FileWrapper(file : java.io.RandomAccessFile) {

  def isEmpty = file.read() < 0

  def next = file.read()
}

在上面的示例中,文件保持其自身状态,但 FileWrapper 仅将方法调用转发给文件对象。

class Account {
  private var balance = 0
  def getBalance = balance
  def deposit(amount: Int): Unit = balance += amount
}

class NoVarAccount {
  val account = new Account()
  def balance = account.getBalance
  def deposit(amount: Int) = account.deposit(amount)
}

现在,NoVarAccount 中没有任何 var,但它仍然是有状态的,因为它将调用转发到确实是有状态的 Account

事实上,您无法保证对同一个对象调用 balance 两次会得到相同的结果。

val account = new NoVarAccount()
account.balance // 0
account.deposit(42)
account.balance // 42

在此示例中,account.balance 不是 引用透明的 ,即您不能将 account.balance 替换为其 return 值,因为它可能变化。

相反,无状态帐户将如下所示:

class StatelessAccount(val balance: Int = 0) {
  def deposit(amount: Int) = new StatelessAccount(balance + amount)
}

或者更通俗地说:

case class StatelessAccount(balance: Int = 0) {
  def deposit(amount: Int) = this.copy(balance = balance + amount))
}

在这种情况下 balance 是引用透明的:

val account = StatelessAccount()
account.balance // 0
val account2 = account.deposit(42)
account2.balance // 42
account.balance // still 0