Lazy Collections

Scala also provides lazy collections, which allow us to postpone the creation to just in time or on-demand. This allows us to express some algorithms or logic in very succinct manner. Let’s see how laziness can be useful.

The following code will help us determine if a given number is prime:

 def​ isPrime(number ​:​ ​Int​) ​=​ {
 val​ sqrtOfNumber ​=​ math.sqrt(number).toInt
 val​ hasFactorsOtherThan1AndItself ​=
  (2 to sqrtOfNumber).exists { i ​=>​ number % i == 0 }
  number > 1 && !hasFactorsOtherThan1AndItself
 }

Suppose we need to determine a list of prime numbers. We could express it like this:

 //Won't work
 def​ primes(number ​:​ ​Int​) ​:​ ​List​[​Int​] ​=​ {
 if​(isPrime(number)) number :: primes(number ...

Get Functional Programming: A PragPub Anthology 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.