[英]Scala's monadic chaining of Try
Consider the following chaining of function f
, g
and h
using monadic for-comprehensions. 考虑使用monadic for-understanding的函数
f
, g
和h
的以下链接。
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: 如果
f
, g
和h
都有签名:
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
,因为存在从Option
到Seq
的隐式转换,但这对于Try
是不可能的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.