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

Thursday, 12 February 2026

AssertJ + AutoCloseableSoftAssertions + Kotlin

I've been playing around with AutoCloseableSoftAssertions, as I don't want to have to remind myself to call .assertAll()

But I also wanted to see if I can replace entire rows of assertThat statements in a simple manner, without many changes.

And I think I have found a way in Kotlin.

Let's start with the basics:

Let's try some SoftAssertions, so we can have many asserts that are all evaluated, instead of the Test stopping upon the first failed assert.

Okay, now AutoCloseableSoftAssertions is a convenient class that calls the .assertAll() as part of the final block in a try-with-resources:

Now, in the case above, we have to prefix our assertThat() calls with "it.". There's one more step that we can use to remove this.

Wrapping all this in a function for easy use will end up in:

Now, a stack of assertThat() statements can be encompassed with assertAll{} without any other changes to get the full advantages of SoftAssertions.

Might be overkill, but this was a fun example in Kotlin.

Try-with-resources

So you might have noticed that AutoClosableSoftAssertions is used in a try-with-resources block.

The small advantage you have, is that if there is an unexpected Exception thrown during your asserts, the ".assertAll()" will still be called, because it's part of the "AutoCloseable.close()".

I don't know how much this advantage is, as the unexpected Exception breaks the test anyways, but there it is.