Rajeev
Rajeev

Reputation: 4992

monad transformers in cats scala

i am trying to learn scala cats library. So i am completely new to functional programming.

Please help me to extract value from below example function :

import cats._
import cats.data._
import cats.syntax._
import cats.implicits._
import cats.functor._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
//import cats.syntax.applicative._


//Here i added test functions to return Either[List[String], A] where left is collecting error list.

case class User(name:String)
case class Users(ppl:List[User])

val testUsers = List(User("test1"), User("test2"))

val func0:Future[Either[List[String], Users]] = () => Future.successful(testUsers.asRight[List[String]])
val func1:(Users => Either[List[String], User]) = (users:Users) => users.ppl(0).asRight[List[String]]

//How to make this function to return Future[Either[List[String], User]] = ???
val res:Future[Either[List[String], Either[List[String], User]]] = EitherT(func0).map(func1).value

Upvotes: 3

Views: 335

Answers (2)

Adam Wayland
Adam Wayland

Reputation: 354

You could also use the pure function to lift the result of func0 into EitherT and then combined it all together in a for-comprehension.

import cats.data._
import cats.implicits._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import cats.instances.future._

case class User(name: String)

case class Users(ppl: List[User])

val testUsers = List(User("test1"), User("test2"))

val func0: Future[Either[List[String], Users]] = () => Future.successful(testUsers.asRight[List[String]])
val func1: (Users => Either[List[String], User]) = (users: Users) => users.ppl.head.asRight[List[String]]

type ListEither[A] = EitherT[Future, List[String], A]

val res: Future[Either[List[String], User]] = for {
  f0 <- func0.pure[ListEither]
  f1 <- EitherT(f0).map(func1).value
} yield f1

Upvotes: 3

Abdhesh kumar
Abdhesh kumar

Reputation: 97

I think, below is an easiest way:

val testUser: Future[Either[List[String], Either[List[String], User]]] = ???

val testUser1: Future[Either[List[String], User]] = testUser.map(_.flatMap(identity))

Upvotes: 2

Related Questions