Как сделать EitherT [Future, String, Int] из Future [Either [String, Int]] с кошками? - PullRequest
2 голосов
/ 21 марта 2019

У меня есть этот код:

  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]. Iхотел бы позвонить powerLevels.get(autobot) в Future.

1 Ответ

1 голос
/ 09 мая 2019

Как отметил @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)
    }

...