Home > Software engineering >  Flatten Either with the same types on the both sides
Flatten Either with the same types on the both sides

Time:09-21

Let's suppose, you have something with type F[Either[T, T]] and you want to flatten Either under your F because both of Either types have the same type and the value doesn't matter for your program.

I found just using Either.fold and use identity function twice for both sides but I think there is should be the better way to do this.

import cats.Functor
import cats.syntax.functor._

import scala.concurrent.Await
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.concurrent.duration.DurationInt
import scala.language.higherKinds

def foo[F[_]: Functor, T](eitherF: F[Either[T, T]]): F[T] =
  eitherF.map(either => either.fold(identity, identity))

val flattenProcess = foo[Future, String](Future(Left[String, String]("left")))
  .flatMap{
    prev =>
      println(prev)
      foo[Future, String](Future(Right[String, String]("rigth")))
  }
println(Await.result(flattenProcess, 10.seconds))
// prints: 
// left
// rigth

here I use Future just for example of some wrapped effect.

Does scala std lib or maybe cats library has something to make it more elegant? Or maybe it is just a problem of my bad design of using Either?

CodePudding user response:

Try Either#merge

eitherF.map(_.merge)

which converts Either[T, T] to T.

  • Related