Scala map on iterator does not produce side effects

前端 未结 2 1251
情歌与酒
情歌与酒 2021-01-12 18:35

Why is it that,

scala> List(1,2,3,4).iterator.map((x: Int) => println(x))

does not print out

1
2
3
4
<
2条回答
  •  情书的邮戳
    2021-01-12 19:14

    Cause map on iterator is lazy and you need some strictness:

    scala> List(1,2,3,4).iterator.map((x: Int) => println(x))
    res0: Iterator[Unit] = non-empty iterator
    
    // nothing actually happened yet, just remember to do this printing things
    
    scala> res0.toList
    1
    2
    3
    4
    res1: List[Unit] = List((), (), (), ())
    

    When you doing foreach on iterator it is quite obvious that you're doing side effects, so lazyness will be undesired. I wouldn't said so about map.

    UPD

    As for your edit: the reason for such behaviour, is that there is implicit call of toString for statement result which in turn stricts the iterator -- try this code on your own:

    scala> { lazyMap(List(1,2,3,4), {(x: Int) => println(x); x + 1}); 1 }
    

    and you'll see that function f is never called

提交回复
热议问题