How do I concisely check for nulls in a long method chain in Scala? -
i'm in situation receive tree data structure outside, can of several different shapes. need sorta switch case depending on kind of tree get. code i'm writing beginning this:
val first = option(root.geta) .flatmap(o => option(o.getb)) .flatmap(o => option(o.getc)) ... val second = option(root.geta) .flatmap(o => option(o.getd)) .flatmap(o => option(o.gete)) ... first.getorelse(second.getorelse...
'first' checks if tree has shape root->a->b->c..., 'second' checks if tree has shape root->a->d->e... etc. feel there ought simpler way express idea in code, since code doing checking null @ every step wrapping , unwrapping options, can't find it.
if geta
etc placeholders parameters getvalue("a")
, can write simple function took root
, ("a", "b", "c")
, walk tree checking nulls along way. assume you've asked question because it's not simple. parameterise on method calls using reflection.
another possibility if tree relatively small or scala code performing majority of work on recursively copy , transform tree more scala-like structure easier process. if feeling particularly twisted, transform xml document , use pattern-match using xml primitives.
alternatively, write custom extractors if there relatively few different getx
functions:
object gota { def unapply(x: thing) = option(x) map {_.geta} }
then code becomes simple pattern-matching this:
root match { case gota(gotb(gotc(x))) => x case gota(gotd(gote(x))) => x }
if node-finding rules irregular it's not amenable of these approaches, can @ least use comprehension that's equivalent code gave, may find more aesthetically pleasing:
val first = { <- option(root.geta) b <- option(a.getb) c <- option(b.getc) } yield c
sadly, because you've heavily anonymised question , don't indicate how many of these lookups required or how complex are, can't recommend specific solution.
Comments
Post a Comment