Principle Software Engineer
Computer scientist Tony Hoare Said:
I call it my billion-dollar mistake. It was the invention of the null reference in 1965
The nullable objects introduces a fundamental problem with type system. For e.g If you declare a object as String, it doesn’t guarantee that the value is real String or null.
We normally skip null checks based on our assumptions in control flow of code. But when we are wrong, the code crashes with Null Pointer Exception. Java 8 introduced Optionals to deal with Nullable objects. But it has some flaws
Wrapping and unwrapping objects into Optional class makes code verbose. Also since it was introduced only in JDK8, you still need to deal with null values returned from older JDK methods.
If you are designing a new language, How will you handle null references? Won’t you add a explicit type definitions for nullables. That’s what Kotlin does.
By default all objects are non-nullable, So you can’t store nulls in them. But if a variable can hold null values, you have to explicitly append
? to indicate it’s nullable. Then, Kotlin forces you to call methods on them using safe call operator
Anything you can do with Java Optionals can be done idiomatic way in Kotlin. For e.g:
Optional.map(...)can be replaced with safe call operation
filterNonNull()method from Collection library.
letfunction in Kotlin.
letfunction is useful to execute a block of code when the value is non-null.
?:operator can also be used to throw exception in case of null
The below code shows Java Optionals and their equivalents in Kotlin.
Kotlin interoperates nicely with Java methods that accepts nullable objects as parameters. It does it using annotations
@NotNull which you can import them from
@NotNull, Kotlin compiler won’t allow you to pass null value.
@Nullable, Kotlin compiler will allow you to pass null value, but it could result in NPE if not handled safely.
The below example shows Java method with annotations and how it behaves when invoked from Kotlin.
@NotNullannotations when calling Java code from Kotlin.
Don’t use nullable types unless it is absolutely needed
Book: Kotlin in Action
Create your free account to unlock your custom reading experience.