scala - Pattern for chaining together calls that take in Options -
i'm finding have chain functions work on option , return different option this:
if(foo.isdefined) somefunctionreturningoption(foo.get) else none is there cleaner way this? pattern gets quite verbose more complicated variables.
i'm seeing fair bit in form handling code has deal optional data. it'll insert none if value none or transformation (which potentially fail) if there value.
you can use flatmap:
foo.flatmap(somefunctionreturningoption(_)) or in for-comprehension:
for { f <- foo r <- somefunctionreturningoption(f) } yield r the for-comprehension preferred when chaining multiple instances of these functions together, de-sugar flatmaps.
Comments
Post a Comment