Skip to content

Instantly share code, notes, and snippets.

@alissonfpmorais
Created January 8, 2019 12:03
Show Gist options
  • Save alissonfpmorais/12fc2258efef197b0a573a41b41f45df to your computer and use it in GitHub Desktop.
Save alissonfpmorais/12fc2258efef197b0a573a41b41f45df to your computer and use it in GitHub Desktop.
Response Type acting like Either pattern
sealed class Response<out S, out E>
data class Success<S>(val success: S) : Response<S, Nothing>()
data class Failure<E>(val error: E) : Response<Nothing, E>()
fun <S, E, R> Response<S, E>.map(f: (S) -> R): Response<R, E> = when (this) {
is Success -> Success(f(this.success))
is Failure -> this
}
fun <S, E, R> Response<S, E>.flatMap(f: (S) -> Response<R, E>): Response<R, E> = when (this) {
is Success -> f(this.success)
is Failure -> this
}
fun <S, E> Response<S, E>.getOrElse(f: (E) -> S): S = when (this) {
is Success -> this.success
is Failure -> f(this.error)
}
fun <S, E> Response<S, E>.doOnSuccess(f: (S) -> Unit): Response<S, E> = when (this) {
is Success -> {
f(this.success)
this
}
is Failure -> this
}
fun <S, E> Response<S, E>.doOnFailure(f: (E) -> Unit): Response<S, E> = when (this) {
is Success -> this
is Failure -> {
f(this.error)
this
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment