Last active
November 12, 2019 13:51
-
-
Save deeperunderstanding/8a57dc64985a7f3936e2f6ccf27e8598 to your computer and use it in GitHub Desktop.
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 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