Skip to content

Instantly share code, notes, and snippets.

@akullpp
Created August 9, 2021 11:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akullpp/83465152c4a272c1bc32ef808317792a to your computer and use it in GitHub Desktop.
Save akullpp/83465152c4a272c1bc32ef808317792a to your computer and use it in GitHub Desktop.
Try
sealed class Try<T> {
companion object {
operator fun <T> invoke(func: () -> T): Try<T> =
try {
Success(func())
} catch (error: Exception) {
Failure(error)
}
object TrySequence {
operator fun <T> Try<T>.component1(): T = when (this) {
is Success -> this.value
is Failure -> throw this.error
}
}
fun <T> sequential(func: TrySequence.() -> T): Try<T> = Try { func(TrySequence) }
}
abstract fun <R> map(transform: (T) -> R): Try<R>
abstract fun <R> flatMap(func: (T) -> Try<R>): Try<R>
abstract fun <R> recover(transform: (Exception) -> R): Try<R>
abstract fun <R> recoverWith(transform: (Exception) -> Try<R>): Try<R>
}
class Success<T>(val value: T) : Try<T>() {
override fun <R> map(transform: (T) -> R): Try<R> = Try { transform(value) }
override fun <R> flatMap(func: (T) -> Try<R>): Try<R> =
Try { func(value) }.let {
when (it) {
is Success -> it.value
is Failure -> it as Try<R>
}
}
override fun <R> recover(transform: (Exception) -> R): Try<R> = this as Try<R>
override fun <R> recoverWith(transform: (Exception) -> Try<R>): Try<R> = this as Try<R>
override fun toString(): String {
return "Success(${value.toString()})"
}
}
class Failure<T>(val error: Exception) : Try<T>() {
override fun <R> map(transform: (T) -> R): Try<R> = this as Try<R>
override fun <R> flatMap(func: (T) -> Try<R>): Try<R> = this as Try<R>
override fun <R> recover(transform: (Exception) -> R): Try<R> = Try { transform(error) }
override fun <R> recoverWith(transform: (Exception) -> Try<R>): Try<R> = Try { transform(error) }.let {
when (it) {
is Success -> it.value
is Failure -> it as Try<R>
}
}
override fun toString(): String {
return "Failure(${error.message})"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment