O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required