Created
February 24, 2017 05:53
-
-
Save kittinunf/f1f67bcc3c91e9d2a508effecae01977 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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