如何用猫从未来制作 BothT[Future, String, Int]?



我有这个代码:

type Response[A] = EitherT[Future, String, A]
val powerLevels = Map(
"Jazz" -> 6,
"Bumblebee" -> 8,
"Hot Rod" -> 10
)
def getPowerLevel(autobot: String): Response[Int] = {
val result = Future {
powerLevels.get(autobot) {
case Some(number) => Right(number)
case None         => Left(s"Can't get connect to $autobot")
}
}
}

我不明白如何将函数getPowerLevel(Future[Either[String, Int]]) 中的计算结果转换为 (Writer 正确转换为Response[Int]类型。我想在Future打电话给powerLevels.get(autobot).

正如@Luis所指出的,您只需要使用EitherT.apply

import cats.data.EitherT
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import cats.implicits._
type Response[A] = EitherT[Future, String, A]
val powerLevels = Map(
"Jazz" -> 6,
"Bumblebee" -> 8,
"Hot Rod" -> 10
)
def getPowerLevel(autobot: String): Response[Int] = {
val result = Future {
powerLevels.get(autobot) match {
case Some(number) => Right(number)
case None         => Left(s"Can't get connect to $autobot")
}
}
EitherT(result)
}

Monad 变压器采用可堆叠的 monad 来返回可组合的 monad。例如,在这种情况下,EitherT[Future, String, A]需要Future[Either[String, A]]来返回可组合的 monad。

尽管其他解决方案恰如其分地满足了这一要求,但我们可以利用condEither的 API 更简洁地编写它,如下所示:

def getPowerLevel(autobot: String): Response[Int] = {
val powerLevel = powerLevels.get(autobot)
EitherT(Future(Either.cond(powerLevel.isDefined, powerLevel.get, s"$autobot unreachable")))
}

相关内容

  • 没有找到相关文章

最新更新