Search code examples
scalafunctional-programmingscala-cats

How to make EitherT[Future, String, Int] from Future[Either[String, Int]] with cats?


I have this code:

  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")
      }
    }

  }

I can't understand how I can convert result of calculation in function getPowerLevel (Future[Either[String, Int]]) to (Writer correctly to Response[Int] type. I'd like to do calling powerLevels.get(autobot) in Future.


Solution

  • As @Luis pointed out, all you need to use is 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)
        }