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

斯卡拉 – 为什么未来有副作用?

发布时间:2020-12-16 09:24:38 所属栏目:安全 来源:网络整理
导读:我正在阅读书籍 FPiS,在页面107上,作者说: We should note that Future doesn’t have a purely functional interface. This is part of the reason why we don’t want users of our library to deal with Future directly. But importantly,even though m
我正在阅读书籍 FPiS,在页面107上,作者说:

We should note that Future doesn’t have a purely functional interface.
This is part of the reason why we don’t want users of our library to
deal with Future directly. But importantly,even though methods on
Future rely on side effects,our entire Par API remains pure. It’s
only after the user calls run and the implementation receives an
ExecutorService that we expose the Future machinery. Our users
therefore program to a pure interface whose implementation
nevertheless relies on effects at the end of the day. But since our
API remains pure,these effects aren’t side effects.

为什么Future还没有纯粹的功能界面?

解决方法

问题在于,由于Future的热切本质,创造一个引起副作用的未来本身也是副作用.

这打破了参考透明度.即如果你创建一个只打印到控制台的Future,将来会立即运行并运行副作用而不需要它.

一个例子:

for {
  x <- Future { println("Foo") }
  y <- Future { println("Foo") }
} yield ()

这导致“Foo”被打印两次.现在,如果Future是引用透明的,我们应该能够在下面的非内联版本中获得相同的结果:

val printFuture = Future { println("Foo") }

for {
  x <- printFuture
  y <- printFuture
} yield ()

然而,这只是打印“Foo”一次,甚至更有问题,无论你是否包含for-expression,它都会打印出来.

使用引用透明表达式,我们应该能够在不改变程序语义的情况下内联任何表达式,Future不能保证这一点,因此它会破坏引用透明性并且本质上是有效的.

(编辑:李大同)

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

    推荐文章
      热点阅读