run.smt.ktest.util.functional.Try.Try.kt Maven / Gradle / Ivy
package run.smt.ktest.util.functional.Try
fun success(value: T): Try = Success(value)
sealed class Try(
val value: T?,
val exception: Throwable?
) {
companion object {
fun of(f: () -> T): Try {
return try {
Success(f())
} catch (e: Throwable) {
Failure(e)
}
}
}
fun map(mapper: (T) -> U): Try =
value?.let(mapper)?.let { Success(it) }
?: Failure(exception ?: IllegalStateException())
fun flatMap(mapper: (T) -> Try): Try =
value?.let(mapper) ?: Failure(exception ?: IllegalStateException())
fun mapTry(mapper: (T) -> U): Try = flatMap { of { mapper(it) } }
}
class Success internal constructor(value: T) : Try(value, null)
class Failure internal constructor(exception: Throwable) : Try(null, exception)