A code example

Let's see how lazy initialization works in Scala and also prove that it is indeed lazy. We will look at an example that calculates a circle area. As we know, the formula is pi * r2. Programming languages have support for mathematical constants and this is not how we will do it in real life. However, the example is still relevant if we're talking about a different constant that is not widely known, or a constant that usually fluctuates around a value, but could be different every day.

At school, we've been taught that pi is equal to 3.14. This is true, however, there are many extra digits after that and if we really care about precision, we will need to account for them as well. For example, pi with 100 digits looks like this: ...

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.