https://kotlinlang.org logo
#stdlib
Title
# stdlib
g

gcx11

01/18/2020, 12:53 PM
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

Dominaezzz

01/18/2020, 1:32 PM
You could do
filter
and then
removeAll
. In general, there isn't a function to mutate a collection while simultaneously creating another.
g

gsala

01/20/2020, 7:11 AM
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