Created
June 4, 2019 16:11
-
-
Save Kvest/c17d7e276328606fe0a8660a7aed00d5 to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* Copyright (C) 2018 Fernando Cejas Open Source Project | |
* | |
* Licensed under the Apache License, Version 2.0 (the "License"); | |
* you may not use this file except in compliance with the License. | |
* You may obtain a copy of the License at | |
* | |
* http://www.apache.org/licenses/LICENSE-2.0 | |
* | |
* Unless required by applicable law or agreed to in writing, software | |
* distributed under the License is distributed on an "AS IS" BASIS, | |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
* See the License for the specific language governing permissions and | |
* limitations under the License. | |
*/ | |
/** | |
* Represents a value of one of two possible types (a disjoint union). | |
* Instances of [Either] are either an instance of [Left] or [Right]. | |
* FP Convention dictates that [Left] is used for "failure" | |
* and [Right] is used for "success". | |
* | |
* @see Left | |
* @see Right | |
*/ | |
sealed class Either<out L, out R> { | |
/** * Represents the left side of [Either] class which by convention is a "Failure". */ | |
data class Left<out L>(val a: L) : Either<L, Nothing>() | |
/** * Represents the right side of [Either] class which by convention is a "Success". */ | |
data class Right<out R>(val b: R) : Either<Nothing, R>() | |
val isRight get() = this is Right<R> | |
val isLeft get() = this is Left<L> | |
fun <L> left(a: L) = Either.Left(a) | |
fun <R> right(b: R) = Either.Right(b) | |
fun either(fnL: (L) -> Any, fnR: (R) -> Any): Any = | |
when (this) { | |
is Left -> fnL(a) | |
is Right -> fnR(b) | |
} | |
} | |
// Credits to Alex Hart -> https://proandroiddev.com/kotlins-nothing-type-946de7d464fb | |
// Composes 2 functions | |
fun <A, B, C> ((A) -> B).c(f: (B) -> C): (A) -> C = { | |
f(this(it)) | |
} | |
fun <T, L, R> Either<L, R>.flatMap(fn: (R) -> Either<L, T>): Either<L, T> = | |
when (this) { | |
is Either.Left -> Either.Left(a) | |
is Either.Right -> fn(b) | |
} | |
fun <T, L, R> Either<L, R>.map(fn: (R) -> (T)): Either<L, T> = this.flatMap(fn.c(::right)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment