Skip to content

Instantly share code, notes, and snippets.

@dylangrijalva
Created January 9, 2023 19:20
Show Gist options
  • Select an option

  • Save dylangrijalva/576b76b67cbed041d0c89dd66a65f908 to your computer and use it in GitHub Desktop.

Select an option

Save dylangrijalva/576b76b67cbed041d0c89dd66a65f908 to your computer and use it in GitHub Desktop.
Either like type in kotlin for handling errors
sealed class Result<out R> {
data class Success<out T>(val data: T) : Result<T>()
data class Error(val message: String, val errorCode: ErrorCode = ErrorCode.UNKNOWN) :
Result<Nothing>() {
companion object {
private const val DEFAULT_ERROR_MESSAGE = "An unknown error has occurred"
fun fromException(exception: Exception): Error {
return Error(exception.message ?: DEFAULT_ERROR_MESSAGE, ErrorCode.UNKNOWN)
}
}
}
override fun toString(): String {
return when (this) {
is Success<*> -> "Success[data=$data]"
is Error -> "<<$errorCode>> Error[message=$message]"
}
}
}
fun <T> fromSuccess(value: T): Result<T> {
return Result.Success(value)
}
fun fromError(error: Exception): Result<Nothing> {
return Result.Error.fromException(error)
}
val Result<*>.isSuccess
get() = this is Result.Success && data != null
fun <T> Result<T>.ifFail(fallback: T): T {
return (this as? Result.Success<T>)?.data ?: fallback
}
fun <T> Result<T>.asNullable(): T? {
return when (this) {
is Result.Success -> this.data
is Result.Error -> null
}
}
fun <A> Result<A>.toOption(): Option<A> {
return if (this is Result.Success) some(this.data) else none()
}
enum class ErrorCode constructor(val message: String) {
UNKNOWN("unknown"),
UNAUTHORIZED("unauthorized")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment