Search code examples
scalascala-catseitherkleisli

How to use Scala Cats' Kleisli with Either


I'm trying to use Kleisli to compose functions returning a monad. It works for an Option:

import cats.data.Kleisli
import cats.implicits._

object KleisliOptionEx extends App {
  case class Failure(msg: String)
  sealed trait Context
  case class Initial(age: Int)                                   extends Context
  case class AgeCategory(cagetory: String, t: Int)                    extends Context
  case class AgeSquared(s: String, t: Int, u: Int)             extends Context

  type Result[A, B] = Kleisli[Option, A, B]
  val ageCategory: Result[Initial,AgeCategory] =
    Kleisli {
      case Initial(age) if age < 18 => {
        Some(AgeCategory("Teen", age))
      }
    }

  val ageSquared: Result[AgeCategory, AgeSquared] = Kleisli {
      case AgeCategory(category, age) =>  Some(AgeSquared(category, age, age * age))
    }

  val ageTotal = ageCategory andThen ageSquared
  val x = ageTotal.run(Initial(5))
  println(x)
}

But I can't make it to work with an Either... :

import cats.data.Kleisli
import cats.implicits._

object KleisliEx extends App {
  case class Failure(msg: String)

  sealed trait Context
  case class Initial(age: Int)                                   extends Context
  case class AgeCategory(cagetory: String, t: Int)                    extends Context
  case class AgeSquared(s: String, t: Int, u: Int)             extends Context

  type Result[A, B] = Kleisli[Either, A, B]

  val ageCategory: Result[Initial,AgeCategory] =
    Kleisli {
      case Initial(age) if age < 18 => Either.right(AgeCategory("Teen", age))
    }

  val ageSquared : Result[AgeCategory,AgeSquared] = Kleisli {
      case AgeCategory(category, age) =>  Either.right(AgeSquared(category, age, age * age))
    }

  val ageTotal = ageCategory andThen ageSquared
  val x = ageTotal.run(Initial(5))

  println(x)
}

I guess Either has two type parameters, and a Kleisle wrapper needs one input and one output type parameters. I don't how could I hide the left type from the Either...


Solution

  • As you correctly state the problem is the fact that Either takes two type parameters while Kleisli expects a type constructor that takes only one. I suggest you take a look at the kind-projector plugin as that deals with your problem.

    You can get around that in several ways:

    If the error type in the Either is always the same you could do:

        sealed trait MyError
        type PartiallyAppliedEither[A] = Either[MyError, A]
        type Result[A, B] = Kleisli[PartiallyAppliedEither, A, B]
        // you could use kind projector and change Result to
        // type Result[A, B] = Kleisli[Either[MyError, ?], A, B]
    

    If the error type needs to be changed you could make your Result type take 3 type parameters instead and then follow the same approach

    type Result[E, A, B] = Kleisli[Either[E, ?], A, B]
    

    Note the ? comes from kind-projector.