简体   繁体   English

为什么Scala Vals默认不偷懒

[英]Why are scala Vals not lazy by default

I have noticed that I almost exclusively use lazy val assignments as they often avoid unnecessary computations, and I can't see that many situations where one would not want to do so (dependency on mutable variables being a notable exceptions of course). 我注意到,我几乎只使用lazy val赋值,因为它们经常避免不必要的计算,而且我看不到很多情况下希望这样做(依赖于可变变量是一个明显的例外)。

It would seem to me that this is one of the great advantages of functional programming and one should encourage its use whenever possible and, if I understood correctly, Haskell does exactly this by default. 在我看来,这是函数式编程的一大优点,应该鼓励在可能的情况下使用它,并且,如果我正确理解的话,Haskell默认情况下正是这样做。

So why are Scala values not lazy by default? 那么,为什么默认情况下Scala值不偷懒? Is it solely to avoid issues relating to mutable variables? 是否仅是为了避免与可变变量有关的问题?

The big difference here between Scala and Haskell is that Scala allows side-effects whereas Haskell does not. Scala和Haskell之间的最大区别是Scala允许副作用,而Haskell不允许。

Laziness results in all sorts of problems in a language which allows side-effects at arbitrary points in the program, as the order in which the side-effects take place becomes non-deterministic. 懒惰会导致一种语言出现各种问题,这种语言会在程序的任意点产生副作用,因为副作用发生的顺序不确定。

Nearly transparent Java interoperability plays a large role in the design of Scala, and Java libraries are typically full of side-effects. 几乎透明的Java互操作性在Scala的设计中扮演着重要角色,并且Java库通常充满副作用。

Scala is a strict language. Scala是一种严格的语言。 Laziness is not only about vals, it's about an evaluation strategy. 懒惰不仅与值有关,而且与评估策略有关。 Should arguments to a function be evaluated before calling the function (what if they are not used?)? 应该调用函数之前对函数的参数求值(如果不使用该参数怎么办?)? In Scala (like most other languages) they are. 在Scala中(就像大多数其他语言一样)。 This strategy carries over to other contexts, including vals and vars. 此策略可扩展到其他上下文,包括val和vars。

It would be awkward to break this rule for vals, but laziness can be useful and provided as an opt-in. 打破此规则的val会很尴尬,但是懒惰可能会有用,可以作为选择加入。

As you noted, dependency on mutable variables is incompatible incompatible with lazy evaluations. 如您所述,对可变变量的依赖与延迟求值不兼容。 Note, that scala is JVM language and Scala programs often use Java libraries, wich are not functional at all. 请注意,scala是JVM语言,Scala程序经常使用Java库,但根本不起作用。 Laziness by default will cause a lot of problems with Java libraries. 默认情况下,惰性会导致Java库出现很多问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM