How Kotlin addresses the “Billion Dollar Mistake”
“I call it my billion-dollar mistake. It was the invention of the null reference in 1965” — Tony Hoare ( inventor of the null reference)
Null Pointer Exceptions(NPE) was called a “Billion Dollar Mistake” by its creator itself. And rightly so, it has brought an enormous pain to the developer for decades now. It’s not that handling an NPE is hard, you can always have try-catch and nullability checks. But in the process, you make your code defensive and bloat the amount of code you write. And in a verbose programming language like Java, you have to write a lot of
if(a!=null){
// do something
}
else{}
or
try {
someObject.doSomething();
} catch(NullPointerException e) {
// do something other
}
Kotlin is made to ease the things for Java developers, and it couldn’t do so without addressing the NPE in Java. This has immensely contributed to the popularity of Kotlin and rightly so, handling NPEs is really easy(and fun) in Kotlin.
The problem with NPEs is that most of the times it is encountered during the runtime. So the code on which the coder was proud when it compiled, falls flat on the face.
Kotlin tries to handle NPEs at compile time. Encountering errors during compile time is much more acceptable than at runtime.
In Kotlin, if you have a variable that could be null somewhere, you have to explicitly declare it in this way:
var a: SomeObject? = null
Now, when you access some method of the object, all you have to do is:
a?.some_method()
The some_method() will only be called when ‘a’ is not null. Isn’t that great? You just saved yourself null checks!
Now suppose, you have a String variable and it can be null sometimes. When it’s not null, you want its length, but if it’s null, you want to have -1. Lets do it in Kotlin:
var string:String?=null
var length=string?.length()?:-1
And of course, you can chain it, like:
person?.name?.first_name?.first_letter
If any one property of the above chain is null, you will get a “null” in return. If not, you will get what you were looking for.
Now let’s do something which NPE lovers will love. Suppose you want the NPE. If you are sure that your object is not going to be a null anywhere, then you can use that object like:
val l = b!!.length
The object with “!!” tells that the object is not expected to be null. And if you call any method of the null object, it will throw an NPE. So if you want NPE, “Man you gotta ask for it! It ain’t gonna appear from nowhere” ;)
NPE handling is just one of the many benefits of Kotlin over Java. So I would recommend trying it once atleast.
So goodbye sleepless nights over Null Pointer Exceptions and a huge round of applause for Kotlin to enable us the power to deal with this ungodly amount of pain NPEs have brought us!
If you enjoyed this post, someone told me hitting the ❤ button is the way to show it ;)