import scala.annotation.tailrec type FlatEither[A] = A match case Either[l, r] => FlatEither[l] | FlatEither[r] case _ => A @tailrec def flatEither[A](a: A): FlatEither[A] = a match case e: Either[?, ?] => e match case Right(r) => flatEither(r) case Left(l) => flatEither(l) case _ => a val flatSimple: Int | String = flatEither(Right(1).withLeft[String]) assert(flatSimple == 1) val e: Either[Either[Boolean, String], Int] = Left(Right("string")) val flat: Boolean | String | Int = flatEither(e) assert(flat == "string")