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.

this the ?. operator proposed c#.

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

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -