Now that we’ve described how Kotlin manages null
values, it’s time to test how Java does it. First, there are neither non-nullable varieties nor null-safe operators in Java. Thus, each variable can probably be null
and must be thought of so.
var MyString str = getMyString(); (1)
var Integer anInt = null; (2)
if (str != null) {
anInt = str.toIntOrNull();
}
1 | String has no toIntOrNull() methodology, so let’s faux MyString is a wrapper kind and delegates to String |
2 | A mutable reference is important |
If you happen to chain a number of calls, it’s even worse as each return worth can probably be null
. To be on the protected aspect, we have to test whether or not the results of every methodology name is null
. The next snippet could throw a NullPointerException
:
var baz = getFoo().getBar().getBaz();
Right here’s the mounted however way more verbose model:
var foo = getFoo();
var bar = null;
var baz = null;
if (foo != null) {
bar = foo.getBar();
if (bar != null) {
baz = bar.getBaz();
}
}
Because of this, Java 8 launched the Non-compulsory kind. Non-compulsory
is a wrapper round a presumably null worth. Different languages name it Perhaps
, Possibility
, and so forth.
Java language’s designers advise {that a} methodology returns:
- Sort
X
ifX
can’t benull
- Sort
Non-compulsory<X>
ifX
could benull
If we modify the return kind of all of the above strategies to Non-compulsory
, we will rewrite the code in a null-safe means – and get immutability on high:
last var baz = getFoo().flatMap(Foo::getBar)
.flatMap(Bar::getBaz)
.orElse(null);
My foremost argument relating to this method is that the Non-compulsory
itself could possibly be null
. The language doesn’t assure that it’s not. Additionally, it’s not suggested to make use of Non-compulsory
for methodology enter parameters.
To deal with this, annotation-based libraries have popped up:
Undertaking | Package deal | Non-null annotation | Nullable annotation |
---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
– |
Nevertheless, completely different libraries work in several methods:
- Spring produces WARNING messages at compile-time
- FindBugs requires a devoted execution
- Lombok generates code that provides a null test however throws a
NullPointerException
if it’snull
anyway - and so forth.

I nonetheless hope it can work out!