加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

斯卡拉 – 任何人都能给我一个很好的例子吗?这种关于“什么使一

发布时间:2020-12-16 18:21:05 所属栏目:安全 来源:网络整理
导读:我不明白这句话的意思(从 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-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的调用,这确实是有状态的.

实际上,您无法保证在同一对象上调用两次平衡将获得相同的结果.

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))
}

在这种情况下,余额是参考透明的:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读