0

I'm doing a null pointer check and would like to know if there is any better way in java 8 other than optional feature

if (cake != null && cake.frosting != null && cake.frosting.berries != null) {
//Do something
}

I'm looking if there is any in-line null pointer check

Learner
  • 31
  • 3
  • Possible duplicate of [Null check in Java 8 Elvis operator?](https://stackoverflow.com/questions/26529091/null-check-in-java-8-elvis-operator) , where the answer from Brian Goetz pretty much rules out the existance of an inline null safe operator in Java, now or in the foreseeable future. – GPI Aug 12 '19 at 14:05

2 Answers2

0

The Elvis operator is what you would want, but it's not part of the Java language. In Groovy you would simply do cake?.frosting?.berries. As you said, you could use Optional if(Optional.ofNullable(cake).map(c -> c.getFosting()).map(f -> f.getBerries()).isPresent()) but that IMHO is quite horrible and not the intended use for Optional. Your if statement, as you wrote it, is simple and easy to read.

Captain
  • 714
  • 4
  • 18
-2

Maybe something like

try{
    cake.frosting.berries.toString();
}catch(NullPointerException npe){
    return;
}
//do something
frank
  • 1,007
  • 1
  • 6
  • 13
  • I think I heard an engineer shrieking somewhere – Rogue Aug 13 '19 at 01:43
  • To expand: you should never catch runtime exceptions (IOOBE, NPE, etc) like this, they're largely indicative of a developer error and add cost to your code if you happen to actually have a null in that chain. _Maybe_ if you never expected them to be null outside of an extreme situation, but even then... – Rogue Aug 13 '19 at 01:45