by jillesvangurp · 2y ago · 0 comments
You can actually write extension functions for nullable types and calling them on a null value does not cause a Nullpointer exception. This also works with Java classes.
For example, there's a CharSequence?.isNullOrBlank(): Boolean function in the Kotlin standard library that allows you to implement a null or blank check on strings. There's a similar isNullOrEmpty function on Lists (and yes, this does work for nullable generic types too).
There are many good reasons to switch from Java to Kotlin. But this is probably one of the bigger ones and genuinely low hanging fruit. Made me feel stupid after years of dealing with Java NPEs routinely and writing a lot of very verbose and needlessly defensive Java code in attempts to avoid them. All that cruft goes away with a proper language. Other languages that do this too are available of course. Pick one. Any one that isn't Java. Dealing with this stuff in 2024 is stupid.
In java I can make my own static function
isNullOrBlank(String input)
Which works on nulls too, right?
It's annoying to have to reference another class - but otherwise it's not much less ergonomic.