Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 473
faoxis Avatar asked Oct 13 '25 05:10

faoxis


1 Answers

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

like image 175
Valy Dia Avatar answered Oct 15 '25 02:10

Valy Dia