简体   繁体   中英

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

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.

So why are Scala values not lazy by default? 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.

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.

Scala is a strict language. 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. This strategy carries over to other contexts, including vals and vars.

It would be awkward to break this rule for vals, but laziness can be useful and provided as an opt-in.

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. Laziness by default will cause a lot of problems with Java libraries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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