简体   繁体   中英

scala: fold over tuple success

With an expression that returns an Either[Fail, TupleX], how do I fold over the result without having to define local vals in the success block?

// 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
    ...
  }
)

像这样

result fold (Conflict(_), { case (email, key) => ... })

Here is a minimal working example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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