Skip to content

Instantly share code, notes, and snippets.

@sorokod
Created February 9, 2022 20:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sorokod/867a64437c680a05200cb8e880cb3b65 to your computer and use it in GitHub Desktop.
Save sorokod/867a64437c680a05200cb8e880cb3b65 to your computer and use it in GitHub Desktop.
/**
* Not sure who the original author is
**/
sealed class Either<out L, out R> {
data class Left<out T>(val value: T) : Either<T, Nothing>()
data class Right<out T>(val value: T) : Either<Nothing, T>()
}
inline fun <L, R, T> Either<L, R>.fold(left: (L) -> T, right: (R) -> T): T =
when (this) {
is Either.Left -> left(value)
is Either.Right -> right(value)
}
inline fun <L, R, T> Either<L, R>.flatMap(f: (R) -> Either<L, T>): Either<L, T> =
fold(left = { this as Either.Left }, right = f)
inline fun <L, R, T> Either<L, R>.map(f: (R) -> T): Either<L, T> =
flatMap { Either.Right(f(it)) }
// #########################################################
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class EitherTest {
private companion object {
fun <T> left(value: T): Either<T, String> =
Either.Left(value)
fun <T> right(value: T): Either<String, T> =
Either.Right(value)
}
@Test
fun map() {
assertEquals(
actual = left(5).map { it + "yes" },
expected = Either.Left(5)
)
assertEquals(
actual = right(5).map { it * 5 },
expected = Either.Right(25)
)
}
@Test
fun flatMap() {
assertEquals(
actual = left(5).flatMap { left(it + "yes") },
expected = Either.Left(5)
)
assertEquals(
actual = right(5).flatMap { left(it * 5) },
expected = Either.Left(25)
)
}
@Test
fun fold() {
assertEquals(
actual = left(5).fold({ "left" }, { "right" }),
expected = "left"
)
assertEquals(
actual = right(5).fold({ "left" }, { "right" }),
expected = "right"
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment