Consider the following chaining of function f
, g
and h
using monadic for-comprehensions.
for {
x <- List ( 11, 22, 33, 44, 55 )
y <- f ( x )
z <- g ( y )
a <- h ( z )
} yield a
If f
, g
and h
all have the signature:
Int => Option [ Int ]
then for-comprehension compiles fine. However if I replace Option [ Int ]
by
Try [ Int ]
, Scala's type-inferencer complains about the line
y <- f ( x )
with the following error message.
error: type mismatch;
found : scala.util.Try[Int]
required: scala.collection.GenTraversableOnce[?]
y <- f ( x )
Why? Both Option [ _ ]
and Try [ _ ]
are (or should be) monads, and should work smoothly as sketched.
You can only use monads of the same kind in a for comprehension. In this case all of your values have to be GenTraversableOnce
, because the first one is. It works with Option
, because there is an implicit conversion from Option
to Seq
, but this is not possible for Try
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With