Last active
June 22, 2022 21:28
-
-
Save dam5s/7fad877656fa891640c115688dbe0f5a to your computer and use it in GitHub Desktop.
Railway oriented programming in Kotlin - This is code accompanying my blog post https://medium.com/@its_damo/error-handling-in-kotlin-a07c2ee0e06f
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
sealed class Result<A, E> { | |
fun <B> map(mapping: (A) -> B): Result<B, E> = | |
when (this) { | |
is Success -> Success(mapping(value)) | |
is Failure -> Failure(reason) | |
} | |
fun <B> bind(mapping: (A) -> Result<B, E>): Result<B, E> = | |
when (this) { | |
is Success -> mapping(value) | |
is Failure -> Failure(reason) | |
} | |
fun <F> mapFailure(mapping: (E) -> F): Result<A, F> = | |
when (this) { | |
is Success -> Success(value) | |
is Failure -> Failure(mapping(reason)) | |
} | |
fun bindFailure(mapping: (E) -> Result<A, E>): Result<A, E> = | |
when (this) { | |
is Success -> Success(value) | |
is Failure -> mapping(reason) | |
} | |
fun orElse(other: A): A = | |
when (this) { | |
is Success -> value | |
is Failure -> other | |
} | |
fun orElse(function: (E) -> A): A = | |
when (this) { | |
is Success -> value | |
is Failure -> function(reason) | |
} | |
fun orNull(): A? = | |
when (this) { | |
is Success -> value | |
is Failure -> null | |
} | |
} | |
data class Success<A, E>(val value: A) : Result<A, E>() | |
data class Failure<A, E>(val reason: E) : Result<A, E>() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very nice code example. I'm using Kotlin for the server-side project and I'm of the idea that Exception is fine for "exceptional" error propagation but in 99% of cases it becomes control flow, and that's not good.
Railway error handling is a very nice pattern and I'll take this code sample as a prototype for our internal lib.