22
loading...
This website collects cookies to deliver better user experience
null
- called the "Billion-Dollar Mistake" by its inventor, C.A.R. Hoare - most programmers are probably intimately familiar with this (and why it might be categorized as a mistake!)if(foo != null) {
// Do something with foo
}
foo
is an object with multiple levels of nested objects? You'd probably agree that it gets a little cumbersome to write something like this:if(foo != null) {
if(foo.bar != null) {
if(foo.bar.baz != null) {
// Now it's safe to use foo.bar.baz
}
}
}
x = foo?.bar?.baz?.doSomething()
?
indicates that the right-hand side should only be evaluated if the left-hand side is not null
. However, if any part of this expression is null
, then x
will be null
.x
should have in case any of the null
checks fail? We could obviously achieve this by checking if x
is null
after the statement and then assigning a different value to it, but if we wanted x
to be a constant, this would not be possible.x = foo?.bar?.baz ? foo?.bar?.baz?.doSomething() : <fallback value>
doSomething()
returns null
, then x
could still be null
! You could work around this by putting ?.doSomething()
before the ?
of the ternary operator, but are we sure it's safe to call doSomething()
more than once? It could have side-effects that introduce subtle bugs into our code or be resource intensive and degrade our application's performance.x = foo?.bar?.baz?.doSomething() ?? <fallback value>
x
can still be a constant, we'll catch any possible null
values in the entire chain, and we're only calling doSomething()
one time (at most).null
and undefined
. Neat, huh??:
- which looks a little bit like the top of Elvis' head (eyes & his signature curly hairdo) - plus, in the Kotlin community we can remember that anything that happens to the right of the operator is what occurs when "Elvis has left the building" (i.e. if you've encountered a null
and left the optional chain) And yes, I know - Programmers can be real nerds sometimes. ;-)??
).