Thread
#stdlib
    g

    gcx11

    2 years ago
    Hello, is there a better/more idiomatic way to write this function? I couldn't find anything like this in the standard library.
    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) }
    }
    Dominaezzz

    Dominaezzz

    2 years ago
    You could do
    filter
    and then
    removeAll
    . In general, there isn't a function to mutate a collection while simultaneously creating another.
    gsala

    gsala

    2 years ago
    You could use
    partition
    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