【发布时间】:2017-06-03 11:24:41
【问题描述】:
在阅读 Maurice Naftalin 的 Mastering Lambdas 时,我遇到了以下示例。 第 3 章第 3.2.4 节是两个例子。
//don't do this - race conditions!
library.stream().forEach(b -> pageCounter += b.getPageCount());
另一个
//formally correct but inefficient and ugly
library.stream().forEachOrdered(b -> { pageCount+=b.getPageCount();});
我的困惑是没有编写上述代码的原因。由于 lambdas 不应该改变状态并且只能访问最终或有效的最终变量,所以上面的代码首先如何有效?
如果我遗漏了什么,谁能帮助我理解。
提前致谢。
【问题讨论】:
-
.forEach(b -> (pageCounter += b.getPageCount()));中的圆括号在此上下文中无效,因为(expression)不是有效的消费者。当需要Consumer时,您需要像.forEach(b -> {pageCounter += b.getPageCount();})这样的花括号或像.forEach(b -> pageCounter += b.getPageCount())这样的没有括号。 -
用正确的语法编辑。