Last active
January 15, 2025 14:33
-
-
Save adriantache/04c17a282635529bab2622264a4f9cd2 to your computer and use it in GitHub Desktop.
Alternative to the default Kotlin result class
This file contains hidden or 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
/** | |
* Alternative to the native Result class, easier to map but less efficient. | |
*/ | |
sealed class Result<T> { | |
data class Success<T>(val value: T) : Result<T>() | |
data class Failure<T>(val error: Error) : Result<T>() | |
val isSuccess | |
get() = this is Success | |
val isFailure | |
get() = this is Failure | |
fun getOrNull(errorAction: (Error) -> Unit): T? { | |
this.onFailure(errorAction) | |
return (this as? Success)?.value | |
} | |
fun errorOrNull(): Error? { | |
return (this as? Failure)?.error | |
} | |
fun <O> map(transformation: (T) -> O): Result<O> { | |
return when (this) { | |
is Failure -> Failure(this.error) | |
is Success -> Success(transformation(this.value)) | |
} | |
} | |
fun onSuccess(action: (T) -> Unit) { | |
if (this is Success) action(this.value) | |
} | |
fun onFailure(action: (Error) -> Unit) { | |
if (this is Failure) action(this.error) | |
} | |
} | |
interface Error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment