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.
r
If you definitely want the list empty when you're done,
dropWhile
isn't the correct analogy, as it will only drop till the return if false. I'm not aware of a built in function, but if you need one at a time processing (which I'm assuming is why you aren't happy with your
drain
solution) you can define your own pretty easy:
Copy code
inline fun <T> MutableList<T>.processAll(action: (T) -> Unit) {
    while (!isEmpty()) action(removeFirst())
}
(Also, if the order doesn't matter and the list can get pretty big,
removeLast()
will likely be more performant than
removeFirst()
.)
You may also want to look in to channels and flows as they're made for handling pipelines like this.
d
Maybe you want the
.removeIf
method?
1
e
removeIf works perfectly, thank you!
thank for the answers ❤️
r
Note that
dropWhile
and
removeIf
are not the same. For example, if you have the following list:
Copy code
val list = mutableListOf(1, 2, 10, 3)
you will see the following:
Copy code
list.dropWhile { it < 5 } == listOf(10, 3)
list.removeIf { it < 5 } == listOf(10)
👍 1
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