The span method lets you split a stream into two parts, by providing a function that detects the dividing line where you want the split to occur. What this doesn’t let you do is to sift through the stream and move each record into the a or b side – you can’t use this to separate even and odd numbers, for instance.
Example:
scala> var (a, b) = Stream.from(1).span(_ < 10)
a: scala.collection.immutable.Stream[Int] = Stream(1, ?)
b: scala.collection.immutable.Stream[Int] = Stream(10, ?)
From this, it appears that it has actually run through 10 elements immediately, not waiting until you actually need one.
We can see it returns what we’d expect:
scala> a.take(10).toList
res26: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
As does b:
scala> b.take(10).toList
res27: List[Int] = List(10, 11, 12, 13, 14, 15, 16, 17, 18, 19)
To show that the even/odd filtering doesn’t work, see the example below. Since the first element is “1” (odd) it automatically goes to the “b” side, and you get an empty list for “a”.
scala> var (a, b) = Stream.from(1).span(_ % 2 == 0)
a: scala.collection.immutable.Stream[Int] = Stream()
b: scala.collection.immutable.Stream[Int] = Stream(1, ?)