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

标签 scala 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 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与它的返回值,因为它可能会有所不同。

相反,无状态帐户将如下所示:
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

关于scala - 谁能给我一个关于 "What makes an object stateful"这种情况的好例子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33306023/

相关文章:

java - 如何在 Java 8 中引用 reduce() 操作的结果?

Scala 类型推断不适用于泛型案例类和 lambda

javascript - 每次调用函数时都会创建新对象

c++ - 用对象填充作为参数传递的数组

javascript - 如何将对象数组转换为自定义分组数组

linux - iptables -j 与 -g 参数

scala - 将 scala 元组打包到自定义类对象

scala - 使用部分应用函数,性能问题

java - java正则表达式匹配器是有状态的吗?

extjs - 在 ExtJS 中使用重新配置创建有状态网格