TimY
TimY

Reputation: 5416

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?

Upvotes: 1

Views: 591

Answers (3)

user1804599
user1804599

Reputation:

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.

Upvotes: 10

Iulian Dragos
Iulian Dragos

Reputation: 5712

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.

Upvotes: 4

Dmitry  Meshkov
Dmitry Meshkov

Reputation: 931

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.

Upvotes: 1

Related Questions