Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way to handle nested nullable objects in scala?

Tags:

scala

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?

like image 728
geoffjentry Avatar asked Dec 09 '22 07:12

geoffjentry


1 Answers

flatMap it:

for {
  a <- Option(foo)
  b <- Option(a.blah)
  c <- Option(b.blarg)
  d <- Option(c.doh)
} yield d
like image 188
kiritsuku Avatar answered Dec 15 '22 00:12

kiritsuku