I would like to map
over a collection with a predicate such that:
- mapping should stop if the predicate is false
- the resulting collection must contain the element for which the predicate was false
- no additional mapping should occur after the predicate was false.
There is Sequence.takeWhile which satisfies 1 and 3 but not 2.
An example with takeWhile
:
val seq = listOf(1, 2, 3, 4).asSequence()
seq.map { println("mapping: $it"); it }
.takeWhile { it < 3 }
.also { println(it.toList()) } }
The output is
mapping: 1
mapping: 2
mapping: 3
[1, 2]
I'd need the result to be [1, 2, 3]