Skip to content

Instantly share code, notes, and snippets.

@deeperunderstanding
Last active November 12, 2019 13:51
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 deeperunderstanding/8a57dc64985a7f3936e2f6ccf27e8598 to your computer and use it in GitHub Desktop.
Save deeperunderstanding/8a57dc64985a7f3936e2f6ccf27e8598 to your computer and use it in GitHub Desktop.
sealed class Try<T> {
companion object {
operator fun <T> invoke(func: () -> T): Try<T> =
try {
Success(func())
} catch (error: Exception) {
Failure(error)
}
}
abstract fun <R> map(transform: (T) -> R): Try<R>
abstract fun <R> flatMap(func: (T) -> 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>
}
}
}
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>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment