I've found myself implementing this in a couple of...
# stdlib
b
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` 😄
Copy code
inline fun <reified T> Iterable<*>.firstIsInstance(): T? {
    for (element in this) {
        if (element is T) {
            return element
        }
    }

    return null
}
1
d
I'd really like this too. Maybe even a contract that allows it.
👍 1
t
I'd rename that to have
orNull
on the end to match the standard library. Maybe
firstInstanceOfOrNull<T>()
?
b
I think that makes sense 👍
c
if you do filterIsInstance and first on a sequence, that would also return on the first match, wouldnt it?