Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Scala: Lazy Evaluation [Presentation]

DZone's Guide to

Scala: Lazy Evaluation [Presentation]

This quick lesson in lazy evaluation covers its benefits and drawbacks your options to implement it in your Scala code.

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

As per Wikipedia, “Lazy Evaluation is an evaluation strategy which delays the evaluation of an expression until its value is needed.” And today most of the modern programming languages support Lazy Evaluation. In contrast with strict or eager evaluation, which computes values as soon as possible, lazy evaluation can certainly deliver a few benefits, such as:

  • Lazy evaluation can help to resolve circular dependencies

  • It can provide performance enhancement by not doing calculations until needed — and they may not be done at all if the calculation is not used.

  • It can increase the response time of applications by postponing the heavy operations until required.

However, lazy evaluation has the drawback that performance may not be predictable — because you cannot say exactly when the value is going to be evaluated.

Scala has the following features to support lazy evaluation.

  1. Lazy vals
    val  can be declared as lazy by using the lazy keyword. The value of val not be initialized until it is called.

    lazy val lval = 10
  2. Call by name parameters
    A method in Scala can accept calls by name parameters. The value of the parameter will only be evaluated whenever it will be used within the method.

    def method(n :=> Int)
  3. Lazy sequences
    Sometimes, we need to allow our client to use as much as they want, and lazy sequences address the problem. Lazy sequence or streams let you define a sequence without any upper bound.

    import Stream.cons
    def stream(n: Int): Stream[Int] = Stream.cons(n, addStream(n+1))

You can also refer to the video for detailed, hands-on example of Scala's lazy evaluation.


Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:
java ,scala ,lazy evaluation ,performance

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}