使用返回Either [Fail,TupleX]的表达式,如何折叠结果而不必在成功块中定义局部值?
// returns Either[Fail, Tuple2[String, String]]
val result = for{
model <- bindForm(form).right
key <- dao.storeKey(model.email, model.password)
} yield (model.email, key)
result fold (
Conflict(_),
tuple2 => { // want to define email/key on this line
val(email,key) = tuple2
...
}
)
答案 0 :(得分:4)
喜欢这个
result fold (Conflict(_), { case (email, key) => ... })
答案 1 :(得分:2)
这是一个最小的工作示例:
case class Conflict(s: String)
def foo(result: Either[Conflict, Tuple2[String, String]]) = {
result.fold(
c => println("left: " + c.toString),
{ case (email, key) => println("right: %s, %s".format(email, key))}
)
}
foo(Left(Conflict("Hi"))) // left: Conflict(Hi)
foo(Right(("email", "key"))) // right: email, key