Reputation: 2582
This might be a silly question, but I've been unsure of it for a while. Let's assume this iterates over our list three times:
def doSomething(list: List[Int]): List[Int] =
list.map(...).flatMap(...).map(...)
If I instead do:
def doSomething(list: List[Int]): List[Int] =
list.toStream.map(...).flatMap(...).map(...).toList
Am I guaranteed a single iteration?
Upvotes: 3
Views: 219
Reputation: 1177
As far as I know, converting to .toStream should do the iteration only once.
Though, the more standard way of doing this is using .view
and then .force
at the end
def doSomething(list: List[Int]): List[Int] =
list.view.map(...).flatMap(...).map(...).force
Using .view
on a collection returns a lazy version of it, and calling .force
on the lazy view creates the collection.
Upvotes: 5