Lazy collections

All these combinators chaining are lovely, but there is a problem. For very large input data structures, this ends up creating intermediate copies.

Let's look at this aspect closely; you'll find that the solution is pretty revealing. Here is the Java code, just to set the stage:

public class LargeLists {
  public static void main(final String[] args) {
    final int take = 5;
    for (int i = 1000, n = 0; i < 1000000 && n < take; ++i) {
      final int j = i + 1;
      final int k = j * 2;
      if (k % 4 != 0) {

Here, we iterate a range of numbers from 1000 to 1000000. And for each number, we add 1 and then multiply the result by 2. If the result is divisible by 4, we discard it. Otherwise, we print the first five numbers ...

Get Scala Functional Programming Patterns 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.