gpt4 book ai didi

scala - 将潜在的 future 恢复到 Cats'EitherT's Left 中?

转载 作者:行者123 更新时间:2023-12-04 21:02:50 24 4
gpt4 key购买 nike

如果我有一个 Future[Either[String, Int]]表示可能的错误消息( String )或成功的计算( Int ),移动 Future 很简单的潜在故障作为错误消息进入左侧:

def handleFailure(fe: Future[Either[String,Int]]) =
f.recover({ case e: Exception => Left(s"failed because ${e.getMessage}"))
我希望 EitherT 存在类似的东西,但也许我就是不知道它叫什么。它相对简单,但涉及拆箱和重新装箱这感觉笨拙的EitherT:
def handleFailureT(fe: EitherT[Future, String, Int]) =
EitherT(handleFailure(et.value)) // See above for handleFailure definition
猫确实添加了 MonadError实例 a while ago ,但它专门用于直接恢复到任何人的 right , 不是为了替换Either 本身。
handleFailureT实现它 Cats,如果是,它叫什么?
理想情况下,它看起来像这样:
class EitherT[F, A, B] {
def handleFailureT[AA](f: PartialFunction[Throwable, AA]): EitherT[F, AA, B] = EitherT(value.recover(f))
}

// Then used like:
val et: EitherT[Future, String, Int] =
EitherT(Future(throw new Exception("an error message"))

et.handleFailure {
case e: Exception => s"Got error with message '${e.message}'"
}
// Now et is Left("Got error with message 'an error message'")

最佳答案

这一点都不明显,但我认为这就是 attemptattemptT是给。例如:

val myTry: Try[Int] = Try(2)
val myFuture: Future[String] = Future.failed(new Exception())
val myTryET: EitherT[Try, Throwable, Int] = myTry.attemptT
val myFutureET: EitherT[Future, Throwable, String] = myFuture.attemptT

// alternatively
val myFutureET: EitherT[Future, Throwable, String] = EitherT(myFuture.attempt)
有一个 PR 将此添加到文档中: https://github.com/typelevel/cats/pull/3178 -- 但它目前没有出现在文档中。但是,您可以在这里看到它: https://github.com/typelevel/cats/blob/master/docs/src/main/tut/datatypes/eithert.md#from-applicativeerrorf-e-to-eithertf-e-a

关于scala - 将潜在的 future 恢复到 Cats'EitherT's Left 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54931204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com