Kotlin's firstNotNullOfOrNull
– mouthful, but useful
#5
robinpokorny
announced in
TIL
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I explore Kotlin built-in methods by scrolling through the list of autocomplete options I get in the IDE.
One time, on a List, I noticed this weirdly named method
firstNotNullOfOrNull
. I had to re-read it to understand the parts. It sure sounds funny. I read about it a bit and yesterday, I finally had a chance to use it.The actual function is quite nice and handy. Let's go by the parts.
1.
first
The function
first
either returns the first element in the List, that is if it is called without arguments. Or you can pass a predicate, in which case it returns the first matching element.With the predicate, it's almost the same as a function you might know:
find
. The only difference is thatfirst
throws if it does not find any matching element, whilefind
returnsnull
. There is an alias tofind
calledfindOrNull
.2.
firstNotNullOf
This is an extension of finding an element by predicate, but instead it returns the first non-null value. So for element you do not care about, you return
null
and for the one you care about you return some value. This value then gets returned as the result offirstNotNullOf
method call. For example, the value can be something that was needed to determine which element is important.In the following, I find the first point that is more than 10 units from the origin and return that distance. So I save some computation.
Here, again, if no such element is found, the system throws an error. I do not generally like that. Fortunately, there is our good old method:
3.
firstNotNullOfOrNull
The method
firstNotNullOfOrNull
will find the first element for which the callback returns something else thannull
and return that. In the case it does not find such element, it returnsnull
itself.I hope it is now clear why I like this method so much. And while it saved only a line or two, it feels like a good addition to the language. I also appreciate that the consistent naming is kept.
Links:
Beta Was this translation helpful? Give feedback.
All reactions