Monday, 16 March 2026

Kotlin: lots of functions

I like Kotlin (sometimes) as it has a large and rich number of convenient functions to use.

In Java, we tend to reach for our Guava1 or Apache Commons Lang2 to get the same functionality.

But it does tend to make it a bit hard to decide which to use, especially as I (as most people I hope) do not know the entire dictionary of available functions in Kotlin.

Luckily there's of course colleagues who can help, and my IDE also does a pretty good task of suggesting better ways.

Case in point:

val items : List<Items> = getItems()
val coupon: Coupon? = items.map { it.coupon }.filter { it != null }.firstOrNull()

I do know the code above can be made simpler.

val items : List<Items> = getItems()
val coupon: Coupon? = items.mapNotNull { it.coupon }.firstOrNull()

There, the mapNotNull() is a very convenient function that I use all the time.

But this time my IDE complained again and told me to use .firstNotNullOfOrNull

val items : List<Items> = getItems()
val coupon: Coupon? = items.firstNotNullOfOrNull { it.coupon }

It's fine by me, to use this, but I didn't know this function exists.

Also, the name seems a bit long and it took a minute to understand the meaning.

References

[1] GitHub - Google Guava
https://github.com/google/guava
[2] Maven Repository - Apache Commons Lang (3)
https://mvnrepository.com/artifact/org.apache.commons/commons-lang3