Created
May 16, 2019 19:00
-
-
Save joelpedraza/22be7db18fac4fa0cb213f31358f5ced 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
@Suppress("NON_PUBLIC_PRIMARY_CONSTRUCTOR_OF_INLINE_CLASS") | |
inline class Result<out T : Any, out E : Any> @PublishedApi internal constructor( | |
@PublishedApi | |
@JvmField | |
internal val value: Any | |
) { | |
companion object { | |
@Suppress("NOTHING_TO_INLINE") | |
inline fun <T : Any, E : Any> Ok(value: T): Result<T, E> = Result(value) | |
@Suppress("NOTHING_TO_INLINE") | |
inline fun <T : Any, E : Any> Err(err: E): Result<T, E> = Result(Result.Error(err)) | |
@Suppress("UNCHECKED_CAST") | |
inline fun <T : Any> of(body: () -> T): Result<T, Throwable> = | |
try { | |
Ok(body()) | |
} catch (tr: Throwable) { | |
Err(tr) | |
} | |
} | |
@Suppress("UNCHECKED_CAST") | |
inline fun <R> reduce(okBody: (T) -> R, errBody: (E) -> R): R = | |
if (value !is Error<*>) okBody(value as T) else errBody(value.err as E) | |
inline val isOk: Boolean | |
get() = reduce( | |
okBody = { true }, | |
errBody = { false } | |
) | |
inline val isErr: Boolean | |
get() = reduce( | |
okBody = { false }, | |
errBody = { true } | |
) | |
inline val okValue: T? | |
get() = reduce( | |
okBody = { it }, | |
errBody = { null } | |
) | |
inline val errValue: E? | |
get() = reduce( | |
okBody = { null }, | |
errBody = { it } | |
) | |
@Suppress("UNCHECKED_CAST") | |
inline fun <R : Any> map(body: (T) -> R): Result<R, E> = reduce( | |
okBody = { Ok(body(it)) }, | |
errBody = { this as Result<R, E> } | |
) | |
@Suppress("UNCHECKED_CAST") | |
inline fun <R : Any> mapErr(body: (E) -> R): Result<T, R> = reduce( | |
okBody = { this as Result<T, R> }, | |
errBody = { Err(body(it)) } | |
) | |
@Suppress("NOTHING_TO_INLINE") | |
inline fun asSequence(): Sequence<T> = reduce( | |
okBody = { sequenceOf(it) }, | |
errBody = { emptySequence() } | |
) | |
@PublishedApi | |
internal class Error<E : Any>( | |
@JvmField | |
val err: E | |
) | |
} | |
@Suppress("NOTHING_TO_INLINE") | |
inline fun <T: Any, E: Any> Result<T, E>.orDefault(defaultValue: T): T = reduce( | |
okBody = { it }, | |
errBody = { defaultValue } | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment