Skip to content

Instantly share code, notes, and snippets.

@soujiro32167
Created October 3, 2022 13:31
Show Gist options
  • Save soujiro32167/0f146108099b6fea24dfd9139a64a6d8 to your computer and use it in GitHub Desktop.
Save soujiro32167/0f146108099b6fea24dfd9139a64a6d8 to your computer and use it in GitHub Desktop.
Flattening an Either tree in Scala 3
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")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment