Let's say you've got a bunch of methods:
def foo() : Try[Seq[String]]
def bar(s:String) : Try[String]
and you want to make a for-comprhension:
for {
list <- foo
item <- list
result <- bar(item)
} yield result
of course this won't compile since Seq cannot be used with Try in this context.
Anyone has a nice solution how to write this clean without breaking it into separate two for's?
I've came across this syntax problem for the thirds time and thought that it's about time to ask about this.
A Try can be converted to an Option, which you can than use in a for-comprehension. E.g.
First time I entered "w", then second time 1234.
IMHO: Try and Seq is more than what you need to define a monad transformer:
Code for library:
and after you can use for-comrehension (just import your library):
and it works for:
You can take advantage of the fact that
Try
can be converted toOption
, andOption
toSeq
:This will return a (possibly empty, if the
Try
s failed)Seq
.If you want to keep all the exception detail, you'll need a
Try[Seq[Try[String]]]
. This can't be done with a single for comprehension, so you're best sticking with plainmap
:If you want to mingle your
Try
s andSeq
s in a different way, things get fiddlier, as there's no natural way to flatten aTry[Seq[Try[String]]]
. @Yury's answer demonstrates the sort of thing you'd have to do.Or, if you're only interested in the side effects of your code, you can just do:
This works because
foreach
has a less restrictive type signature.