I'm working with scala and recently inherited some Java code which needs to be grafted in and unfortunately rewriting it in Scala isn't in the cards. It has a deeply nested object structure, and any level can be null. Often I only care about the values deep within the nesting.
Ideally, I'd do something like this:
Option(foo.blah.blarg.doh)
But if any of foo.blah.blarg is null, this will generate a NPE.
For now I've taken to wrapping it in a Try:
Try(Option(foo.blah.blarg.doh)).getOrElse(None)
Note that using .toOption doesn't work quite right as it can lead to a Some(null) if the final bit of the chain is null.
I'm not particularly fond of this construct, any other ideas out there?
flatMap it:
for {
a <- Option(foo)
b <- Option(a.blah)
c <- Option(b.blarg)
d <- Option(c.doh)
} yield d
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With