Hey! Is there a native Kotlin function like dropWh...
# getting-started
e
Hey! Is there a native Kotlin function like dropWhile that doesn’t create a new list?
n
What are you trying to achieve exactly? Do you want a mutating function, or chaining? If you want chaining without intermediary collections, you can use the
asSequence
function. Kotlin generally prefers immutable collections, and non-mutating functions. Or perhaps some of the
remove
-like functions on
MutableCollection
would be of use to you?
e
I want to process and remove items from a mutable list so that, once all processing is complete, the original list ends up empty, like my custom extension drain() at right.
d
Maybe you want the
.removeIf
method?
✅ 1
e
removeIf works perfectly, thank you!
thank for the answers ❤️
d
Fair point.
Maybe also consider using indexOf and subList() as alternatives
e
However,
dropWhile
doesn’t modify the list in place; it returns a new one. In other contexts, it works fine too.
g
All Kotlin collection functions create new list, it's intentional to avoid mutability
d
Personally, I only switch to mutable lists when there is a proven performance concern, or if the size of the list is known to be "huge" (subjectively).
➕ 2
g
Yep, exactly, the same reason why many collection utils do not exist for Array, that it concidered more low level So I think it's really a matter to have minimal list of utils for mutable primitives, because they not intended to be used as often and extensively as read only