0

I am experimenting with below code:

def TestRun(n: Int): Unit = {
      (1 to n)
        .grouped(4)
        .map(grp => { println("Group length is: " + grp.length)})
    }

TestRun(100)

And I am a bit surprised that I am not able to see any output of println after executing the program. Code compiled successfully and ran, but without any expected output.

Kindly point me what mistake I am doing.

Andronicus
  • 25,419
  • 17
  • 47
  • 88
Abhay Kumar
  • 522
  • 3
  • 9

1 Answers1

3

The reason there is no output is that Range gives an Iterator which is lazy. This means that it won't create any data until it is asked. Likewise the grouped and map methods also return a lazy Iterator, so the result is a Iterator that will return a set of values only when asked. TestRun never asks for the data, so it is never generated.

One way round this is to use foreach rather than map because foreach is eager (the opposite of lazy) and will take each value from the Iterator in turn.

Another way would be to force the Iterator to become a concrete collection using something like toList:

def TestRun(n: Int): Unit = {
  (1 to n)
    .grouped(4)
    .map(grp => { println("Group length is: " + grp.length)})
    .toList
}

TestRun(100)
Tim
  • 26,753
  • 2
  • 16
  • 29