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

Bornyls Deen

05/27/2020, 8:16 PM
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

Dominaezzz

05/27/2020, 8:22 PM
I'd really like this too. Maybe even a contract that allows it.
👍 1
t

todd.ginsberg

05/27/2020, 10:29 PM
I'd rename that to have
orNull
on the end to match the standard library. Maybe
firstInstanceOfOrNull<T>()
?
b

Bornyls Deen

05/28/2020, 8:24 AM
I think that makes sense 👍
c

christophsturm

05/28/2020, 9:47 AM
if you do filterIsInstance and first on a sequence, that would also return on the first match, wouldnt it?