<@U5QK61PK7> There is firstOrNull if you want to g...
# getting-started
g
@jasonlow There is firstOrNull if you want to get nullable value. Reason - you can use
first
and get nonnull result
j
Thanks for the reply @gildor, but I don’t really understand what you meant by
Copy code
you can use `first` and get nonnull result
Doesn’t that mean I am guaranteed a result? But using ‘first’ clearly throws an exception, meaning there’s still a chance my result will be a null.
The only use case I can think for ‘first’ is if my dataset is guaranteed to have some data that might match my predicate.
g
No, of course it doesn’t guarantee result, it’s just different approaches, sometimes you want to get item or throw exception otherwise, so result will be non-nullable (so you shouldn’t handle possible nullable values) If null result is okay for you case, just use firstOrNull
v
or
find
👍 1
j
I see, thanks for the help @gildor!
@voddan, what is the difference between
firstOrNull
and
find
?
m
find
will iterate the whole list trying to find the element that matches the predicate
firstOrNull
won't, as it will return on the 1st element or null right away
j
@menegatti Forgive me if I’m just blind or dumb, but from the source code it seems that
find
is just wrapping around
firstOrNull
Copy code
/**
 * Returns the first element matching the given [predicate], or `null` if no such element was found.
 */
@kotlin.internal.InlineOnly
public inline fun <T> Iterable<T>.find(predicate: (T) -> Boolean): T? {
    return firstOrNull(predicate)
}
m
oh yeah, we are talking about different
firstOrNull
one that takes the parameter, which is exactly what you found
and one that doesn't, which returns the first element of the list
so yes, if you're using
firstOrNull
with a certain predicate, then it is the exact same thing as
find
g
same thing as
firstOrNull
as
first
.
first
is just alias for
firstOrNull
m
I meant to say find, fixed now
v
There was an argument about naming because
find
is used in other langs, but
firstOrNull
is more explicit and "kotlin way"
do
find
is an alias to
findOrNull
(it is also shorter)
AFAIK this is the only place in stdlib where functions duplicate each other