Null is your friend, not a mistake

Not really.

It is normal when some operations fail at runtime on certain values of a type (like division by zero), but when a value leads to runtime failure of all operations, it shows that the value should not belong to this type in the first place.

All those NPEs in Java programs indicate an obvious flaw in Java type-system.

More type-safe programming languages, like Kotlin, fix this flaw by properly incorporating the concept of null into the type system.

Adding inspections and warning does help, too, but it is not enough.

Clearly, a sound type system must only allow such values of type String that can support its operations, so in Kotlin putting null into a variable of type String is not just a warning, but a type error akin to assigning an integer value 42 to a variable of type String.

Proper null support in type system is a game-changer for API design.

There is no reason whatsoever to fear null anymore.

Having some functions that return a nullable type String?.side-by-side with others that return non-null String is as normal as having some functions that return String side-by-side with others that return Int.

They are simply different types with different and safe sets of operations available for them.

Type-safe null is better, more efficient, and less verbose alternative to represent all sorts of “missing results”.

Look at Kotlin standard library for inspiration, for example.

There is String.

toIntOrNull() function that parses a string to an integer, if possible, or returns null if not.

It is joy to use.

Writing a command-line application that takes an integer parameter and properly complains on its absence is easy:fun main(args: Array<String>) { val id = args.


toIntOrNull() ?: error("id expected") // .

}Embrace null in your API design.

Null is your friend with Kotlin.

There is no reason to fear it and no reason to work around it with “null object” pattern or wrappers, let alone with exceptions.

Proper use of nulls in your APIs results in more readable and safer code, free from boilerplate.


. More details

Leave a Reply