Skip to content

Instantly share code, notes, and snippets.

@ilhikki
Created November 4, 2021 06:56
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 ilhikki/fad115495ff78564a1e605eef11a864a to your computer and use it in GitHub Desktop.
Save ilhikki/fad115495ff78564a1e605eef11a864a to your computer and use it in GitHub Desktop.
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