java - How to implement this nested flow with optionals? -
i've have method takes string
input , should return string
.
the following ascii art presents logical flow:
option<a> opta = finder.finda(input); opta /\ isempty() / \ isdefined() / \ "err_1" option<b> optb = finder.findb(opta.get().bid); / \ isempty() / \ isdefined() / \ "err_2" opt2.get().id
basically given input
i'm looking a
object returned wrapped in option
. a
present i'm looking b
- wrapped in option
too, otherwise return err_1
. if b
present return it's id, otherwise return err_2
.
i'm wondering how implemented using optionals (or pattern matching maybe?) in nice , concise way (without ifology) - possibly in one-liner.
could please suggest something?
source code try out can found here.
it looks have 3 possible exit points:
- opta empty -> "err_1"
- opta not empty && optb empty -> "err_2"
- both not empty -> optb.get().bid
you can achieve doing javaslang:
opta .map(a -> finder.findb(a.bid) .map(b -> b.bid) .getorelse("err_2")) .getorelse("err_1");
if opta
empty, jump straight orelse("err_1")
if opta
not empty, using value stored inside getting value b.bid
or "err_2"
in case of optb
emptiness.
also, in pure java 8, this:
opta .map(a -> finder.findb(a.bid) .map(b -> b.bid) .orelse("err_2")) .orelse("err_1");
Comments
Post a Comment