我有此代码:
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]]
)中的计算结果转换为(正确将书写器转换为Response[Int]
类型。我想调用{{ 1}}在powerLevels.get(autobot)
中。
答案 0 :(得分:1)
正如@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)
}
答案 1 :(得分:0)
Monad 转换器采用可堆叠的 monad 来返回可组合的 monad。 例如,在这种情况下,EitherT[Future, String, A]
将采用 Future[Either[String, A]]
来返回可组合的 monad。
尽管其他解决方案恰如其分地满足了这一要求,但我们可以使用 cond
中的 Either
API 将其编写得更简洁:
def getPowerLevel(autobot: String): Response[Int] = {
val powerLevel = powerLevels.get(autobot)
EitherT(Future(Either.cond(powerLevel.isDefined, powerLevel.get, s"$autobot unreachable")))
}