gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:44:41 24 4
gpt4 key购买 nike

我不明白这句话的意思(来自 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com