Skip to content

Commit 347fafc

Browse files
committed
Add flatmap and map to monadic type Either<L, R>
1 parent 03f9ff8 commit 347fafc

File tree

1 file changed

+17
-1
lines changed
  • app/src/main/kotlin/com/fernandocejas/sample/core/functional

1 file changed

+17
-1
lines changed

app/src/main/kotlin/com/fernandocejas/sample/core/functional/Either.kt

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,28 @@ sealed class Either<out L, out R> {
3131
data class Right<out R>(val b: R) : Either<Nothing, R>()
3232

3333
val isRight get() = this is Right<R>
34-
3534
val isLeft get() = this is Left<L>
3635

36+
fun <L> left(a: L) = Either.Left(a)
37+
fun <R> right(b: R) = Either.Right(b)
38+
3739
fun either(fnL: (L) -> Any, fnR: (R) -> Any): Any =
3840
when (this) {
3941
is Left -> fnL(a)
4042
is Right -> fnR(b)
4143
}
4244
}
45+
46+
// Credits to Alex Hart -> https://proandroiddev.com/kotlins-nothing-type-946de7d464fb
47+
// Composes 2 functions
48+
fun <A, B, C> ((A) -> B).c(f: (B) -> C): (A) -> C = {
49+
f(this(it))
50+
}
51+
52+
fun <T, L, R> Either<L, R>.flatMap(fn: (R) -> Either<L, T>): Either<L, T> =
53+
when (this) {
54+
is Either.Left -> Either.Left(a)
55+
is Either.Right -> fn(b)
56+
}
57+
58+
fun <T, L, R> Either<L, R>.map(fn: (R) -> (T)): Either<L, T> = this.flatMap(fn.c(::right))

0 commit comments

Comments
 (0)