Created
November 4, 2021 06:56
-
-
Save ilhikki/fad115495ff78564a1e605eef11a864a 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
class ResultEliminatorCurrying0<T, R> { | |
@Suppress("FunctionName") | |
fun OK(ok: (T) -> R): ResultEliminatorCurrying1<T, R> = ResultEliminatorCurrying1(ok) | |
} | |
class ResultEliminatorCurrying1<T, R>(internal val ok: (T) -> R) | |
@Suppress("FunctionName") | |
infix fun <T, R> ResultEliminatorCurrying1<T, R>.FAIL(fail: (Throwable) -> R): ResultEliminator<T, R> = ResultEliminator(ok, fail) | |
class ResultEliminator<T, R>(val ok: (T) -> R, val fail: (Throwable) -> R) | |
fun <T> ofSuccess(data: T): Result<T> = Result(Wrapper(data), null, true) | |
fun <T> ofFail(throwable: Throwable): Result<T> = Result(null, Wrapper(throwable), false) | |
class Wrapper<T>(val value: T) | |
class Result<T> internal constructor(private val data: Wrapper<T>?, private val err: Wrapper<Throwable>?, private val success: Boolean) { | |
fun <R> match(eliminatorFactory: ResultEliminatorCurrying0<T, R>.() -> ResultEliminator<T, R>): R { | |
val eliminator = eliminatorFactory(ResultEliminatorCurrying0()) | |
return if (success) { | |
eliminator.ok(data!!.value) | |
} else { | |
eliminator.fail(err!!.value) | |
} | |
} | |
} | |
fun main() { | |
val result: Int? = ofSuccess(null).match { | |
OK { | |
it | |
} FAIL { | |
throw it | |
} | |
} | |
println(result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment