Hello, is there a better/more idiomatic way to wri...
# stdlib
g
Hello, is there a better/more idiomatic way to write this function? I couldn't find anything like this in the standard library.
Copy code
inline fun <T, C: MutableCollection<T>> MutableList<T>.retrieveAllTo(collection: C, predicate: (T) -> Boolean): C {
    val iterator = this.listIterator()

    for (item in iterator) {
        if (predicate(item)) {
            collection.add(item)
            iterator.remove()
        }
    }

    return collection
}

inline fun <T> MutableList<T>.retrieveAll(predicate: (T) -> Boolean): List<T> {
    return mutableListOf<T>().also { retrieveAllTo(it, predicate) }
}
d
You could do
filter
and then
removeAll
. In general, there isn't a function to mutate a collection while simultaneously creating another.
g
You could use
partition
Copy code
inline fun <T> Array<out T>.partition(
    predicate: (T) -> Boolean
): Pair<List<T>, List<T>>
To get the original list and the resulting list in a pair
👍 3