简体   繁体   English

斯卡拉的尝试的monadic链接

[英]Scala's monadic chaining of Try

Consider the following chaining of function f , g and h using monadic for-comprehensions. 考虑使用monadic for-understanding的函数fgh的以下链接。

  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: 如果fgh都有签名:

  Int => Option [ Int ] 

then for-comprehension compiles fine. 然后for-comprehension编译好。 However if I replace Option [ Int ] by Try [ Int ] , Scala's type-inferencer complains about the line 但是,如果我用Try [ Int ]替换Option [ Int ] ,Scala的类型推理器会抱怨该行

  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. Option [ _ ]Try [ _ ]都是(或应该是)monad,并且应该如草绘一样顺畅。

You can only use monads of the same kind in a for comprehension. 您只能在理解中使用相同类型的monad。 In this case all of your values have to be GenTraversableOnce , because the first one is. 在这种情况下,您的所有值都必须是GenTraversableOnce ,因为第一个值是。 It works with Option , because there is an implicit conversion from Option to Seq , but this is not possible for Try . 它适用于Option ,因为存在从OptionSeq的隐式转换,但这对于Try是不可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM