Created
January 8, 2019 12:03
-
-
Save alissonfpmorais/12fc2258efef197b0a573a41b41f45df to your computer and use it in GitHub Desktop.
Response Type acting like Either pattern
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 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