Created
September 28, 2025 10:11
-
-
Save ajinkya5130/a5df6c9c003ed50695c95fe77e763dd6 to your computer and use it in GitHub Desktop.
Result Wrapper 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
| sealed interface DataError: Error { | |
| enum class Remote: DataError{ | |
| BAD_REQUEST, | |
| UNAUTHORIZED, | |
| REQUEST_TIMEOUT, | |
| FORBIDDEN, | |
| CONFLICT, | |
| TOO_MANY_REQUESTS, | |
| NO_INTERNET_CONNECTION, | |
| PAYLOAD_TOO_LARGE, | |
| NOT_FOUND, | |
| SERIALIZATION_ERROR, | |
| SERVER_ERROR, | |
| SERVICE_UNAVAILABLE, | |
| TIMEOUT, | |
| UNKNOWN | |
| } | |
| enum class Local: DataError{ | |
| DISK_FULL, | |
| FILE_NOT_FOUND, | |
| UNKNOWN | |
| } | |
| } |
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
| interface Error |
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
| sealed interface Result<out D,out E: Error> { | |
| data class Success<out D>(val data:D): Result<D, Nothing> | |
| data class Failure<out E: Error>(val error:E): Result<Nothing,E> | |
| } | |
| /** | |
| @param T - Data, | |
| E - Error, | |
| R - Result | |
| take T and return R and again take R and return R and E | |
| * */ | |
| inline fun <T,E: Error,R> Result<T,E>.map(map:(T) -> R): Result<R,E>{ | |
| return when(this){ | |
| is Result.Success -> Result.Success(map(data)) | |
| is Result.Failure -> Result.Failure(error) | |
| } | |
| } | |
| inline fun <T,E: Error> Result<T,E>.onSuccess(action:(T) -> Unit): Result<T,E>{ | |
| return when(this){ | |
| is Result.Success -> { | |
| action(data) | |
| this | |
| } | |
| is Result.Failure -> this | |
| } | |
| } | |
| inline fun <T,E: Error> Result<T,E>.onFailure(action:(E) -> Unit): Result<T,E>{ | |
| return when(this){ | |
| is Result.Success -> this | |
| is Result.Failure -> { | |
| action(error) | |
| this | |
| } | |
| } | |
| } | |
| typealias EmptyResult<E> = Result<Unit,E> | |
| inline fun <T,E: Error> Result<T,E>.asEmptyResult(): EmptyResult<E>{ | |
| return map { } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment