Skip to content

Instantly share code, notes, and snippets.

@jose-almir
Last active December 1, 2020 17:50
Show Gist options
  • Save jose-almir/b1eff42eae5361f43dec3559153d2ddc to your computer and use it in GitHub Desktop.
Save jose-almir/b1eff42eae5361f43dec3559153d2ddc to your computer and use it in GitHub Desktop.
Simple Either implementation in Kotlin with fold method
sealed class Either<L, R> {
inline fun <B> fold(onLeft: (L) -> B, onRight: (R) -> B): B = when (this) {
is Left -> onLeft(this.value)
is Right -> onRight(this.value)
}
operator fun not() = fold(::id, ::id)
}
class Left<L, R>(val value: L) : Either<L, R>()
class Right<L, R>(val value: R) : Either<L, R>()
fun <T> id(id: T): T = id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment