Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala's monadic chaining of Try

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.

like image 431
Martin Berger Avatar asked Jun 28 '15 08:06

Martin Berger


1 Answers

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.

like image 186
drexin Avatar answered Oct 18 '22 13:10

drexin