Scala monadic chain Try

Consider the following chain of functions f , g and h using monadic concepts.

  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 a signature:

  Int => Option [ Int ] 

then for-understanding a fine compiles. However, if you replace Option [ Int ] with Try [ Int ] , the Scala type-inferencer complains about the string

  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, like drafts.

+6
source share
1 answer

You can only use monads of the same type for understanding. In this case, all of your values โ€‹โ€‹should 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 .

+9
source

Source: https://habr.com/ru/post/989880/


All Articles