Thread
#stdlib
    Bornyls Deen

    Bornyls Deen

    2 years ago
    I've found myself implementing this in a couple of different projects now... do you guys think there might be a place for it in the standard library? The closest I've got using the existing functions is chaining
    filterIsInstance
    and
    first
    but I imagine this is a little better performance wise as we are returning after the first match. It's like
    first
    is to
    filter
    ... firstIsInstance/filterIsInstance 😄
    inline fun <reified T> Iterable<*>.firstIsInstance(): T? {
        for (element in this) {
            if (element is T) {
                return element
            }
        }
    
        return null
    }
    Dominaezzz

    Dominaezzz

    2 years ago
    I'd really like this too. Maybe even a contract that allows it.
    todd.ginsberg

    todd.ginsberg

    2 years ago
    I'd rename that to have
    orNull
    on the end to match the standard library. Maybe
    firstInstanceOfOrNull<T>()
    ?
    Bornyls Deen

    Bornyls Deen

    2 years ago
    I think that makes sense 👍
    christophsturm

    christophsturm

    2 years ago
    if you do filterIsInstance and first on a sequence, that would also return on the first match, wouldnt it?