Reputation: 159
I would like to filter a list and log the items which fell through the filter, similar to this:
val evenNumbers = (1..10)
.filter { it % 2 == 0 }
.onFallThrough { println("dropped $it") } // wishful Kotlin
.toList()
This should then lead to the following output:
dropped 1
dropped 3
dropped 5
dropped 7
dropped 9
as well as all even numbers collected in the list evenNumbers
.
Looking through the manual page on Sequences, I couldn't find anything that seemed to do this. Is there a way to achieve this in Kotlin?
Upvotes: 1
Views: 397
Reputation: 82117
I would use partition
:
val evenNumbers = (1..10)
.partition { it % 2 == 0 }
.let {
println("dropped ${it.second}")
it.first
}
It returns a Pair
with its first
property containing all elements that matched the condition and its second
property containing the elements that did not match.
Upvotes: 5