【问题标题】:How to make EitherT[Future, String, Int] from Future[Either[String, Int]] with cats?如何用猫从 Future[Either[String, Int]] 制作 EitherT[Future, String, Int]?
【发布时间】:2019-08-12 18:15:08
【问题描述】:

我有这个代码:

  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)

【问题讨论】:

  • 您在get(autobot) 之后缺少一个match,要创建一个EitherT,您只需将result 传递给构造函数 .例如。 new EitherT(result).
  • 链接到描述如何执行此操作的文档:typelevel.org/cats/datatypes/…

标签: scala functional-programming scala-cats


【解决方案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)
    }

【讨论】:

    【解决方案2】:

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

    虽然其他解决方案可以很好地满足这一要求,但我们可以使用Either 中的cond API 来更简洁地编写它:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-03
      • 2019-06-19
      • 2018-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多