Skip to content

Instantly share code, notes, and snippets.

@kittinunf
Created February 24, 2017 05:53
Show Gist options
  • Save kittinunf/f1f67bcc3c91e9d2a508effecae01977 to your computer and use it in GitHub Desktop.
Save kittinunf/f1f67bcc3c91e9d2a508effecae01977 to your computer and use it in GitHub Desktop.
sealed class Either<out L, out R> {
companion object {
fun <L> left(left: L): Left<L, Nothing> = Left(left)
fun <R> right(right: R): Right<Nothing, R> = Right(right)
}
fun left(): L? = when (this) {
is Left -> this.l
is Right -> null
}
fun right(): R? = when (this) {
is Left -> null
is Right -> this.r
}
operator abstract fun component1(): L?
operator abstract fun component2(): R?
fun <X> fold(fl: (L) -> X, fr: (R) -> X): X = when (this) {
is Left -> fl(l)
is Right -> fr(r)
}
fun swap(): Either<R, L> = when (this) {
is Left -> Right(this.l)
is Right -> Left(this.r)
}
class Left<out L, out R>(val l: L) : Either<L, R>() {
override fun component1(): L = l
override fun component2(): R? = null
override fun equals(other: Any?): Boolean = when (other) {
is Left<*, *> -> l == other.l
else -> false
}
override fun toString(): String = "Either.Left($l)"
}
class Right<out L, out R>(val r: R) : Either<L, R>() {
override fun component1(): L? = null
override fun component2(): R = r
override fun equals(other: Any?): Boolean = when (other) {
is Right<*, *> -> r == other.r
else -> false
}
override fun toString(): String = "Either.Right($r)"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment