4 ms·
Kotlin makes nullability part of the typesystem. It's a good reference for what would happen if Java did this better because if you are using Java you can just
by jillesvangurp 3y ago
Kotlin makes nullability part of the typesystem. It's a good reference for what would happen if Java did this better because if you are using Java you can just switch to Kotlin and experience this in your own code base (you can mix Java and Kotlin code easily).
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.
- fyve 3y agoCharSequence?.isNullOrBlank() 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.
- usrusr 3y agoYou can, you can even call the kotlin version that way if it happens to be on the classpath, but it's truly horrible ergonomics if for every call you have to guess between class-ref-otherargs and ref-otherargs forms. It's one of those little cuts you grow numb to.
- severino 3y agoCharSequence is the base class that things like java.lang.String inherit. So I understood that as an instance method you can call like "foo".isNullOrBlank() (in Kotlin syntax)
- usrusr 3y agoBut null is still null, a very special non-reference signifying absence. And not some pretend-object that walks like a valid reference, swims like a valid reference, but somehow doesn't quite quack like one. The problems surfacing as an NPE don't magically go away by null-less approaches, they just bite you at different times, in different form. Sometimes sooner, which is good, but sometimes also later. Java made null worse by not taking nullability into the type system (these days nullability annotations do a tolerable job at pretending it was) and lacking scope functions that make it easy to check without the eyesore of flooding local scope with names. Kotlin is really awesome for not falling into the trap of chasing the pipe dream of a world without absence.