Is there an out of the box way to take from an Ite...
# announcements
r
Is there an out of the box way to take from an Iterable until a predicate is satisfied, including the element that first satisfies the predicate? Something like:
Copy code
val xs = listOf("a", "e", "c", "b", "d")
xs.takeUntil { it == "c" } == listOf("a", "e", "c")
s
is
takeWhile {}
not what you’re looking for?
or I guess, you’re looking for the inverse of takeWhile
r
No, takeWhile isn’t inclusive
n
I thought I might be able to come up with a one-liner for a list, but I think I hate it
Copy code
val list = listOf("foo")
list.take(list.indexOfFirst { it == "bar" }.takeIf { it >= 0 }?.let { it + 1 } ?: list.size)
e
honestly I'd like this solution the best, don't know why nothing like it is listed...
Copy code
buildList {
    for (elem in list) {
        add(elem)
        if (predicate(elem)) break
    }
}
works with
sequence
too
👍 4
n
Well, for a sequence you'd want to return another sequence, not a list
e
well yes, and you'd use
emit
instead of
add
, but either way you don't need to keep a Boolean var