This is a matter of consistency. Things are what they are and return things like them. You can depend on him.
The difference you make here is rigor. The strict method is evaluated immediately, and the non-strict method is evaluated as necessary. This has consequences. Take this simple example:
def print5(it: Iterable[Int]) = { var flag = true it.filter(_ => flag).foreach { i => flag = i < 5 println(i) } }
Test it with these two collections:
print5(List.range(1, 10)) print5(Stream.range(1, 10))
List strict here, so its methods are strict. Conversely, Stream is non-strict, so its methods are not strict.
So this has nothing to do with Iterable all - because List and Stream are Iterable . Changing the type of collection return can cause all sorts of problems - at least this will make the task of maintaining a constant data structure more difficult.
On the other hand, there are advantages to delaying certain operations, even with strict collection. Here are some ways to do this:
// Get an iterator explicitly, if it going to be used only once def print5I(it: Iterable[Int]) = { var flag = true it.iterator.filter(_ => flag).foreach { i => flag = i < 5 println(i) } } // Get a Stream explicitly, if the result will be reused def print5S(it: Iterable[Int]) = { var flag = true it.toStream.filter(_ => flag).foreach { i => flag = i < 5 println(i) } } // Use a view, which provides non-strictness for some methods def print5V(it: Iterable[Int]) = { var flag = true it.view.filter(_ => flag).foreach { i => flag = i < 5 println(i) } } // Use withFilter, which is explicitly designed to be used as a non-strict filter def print5W(it: Iterable[Int]) = { var flag = true it.withFilter(_ => flag).foreach { i => flag = i < 5 println(i) } }
source share