Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 1 | package kotlinx.coroutines.experimental |
| 2 | |
Roman Elizarov | dbcd841 | 2017-01-19 10:36:16 +0300 | [diff] [blame] | 3 | public class Try<out T> private constructor(private val _value: Any?) { |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 4 | private class Fail(val exception: Throwable) { |
| 5 | override fun toString(): String = "Failure[$exception]" |
| 6 | } |
| 7 | |
| 8 | public companion object { |
Roman Elizarov | dbcd841 | 2017-01-19 10:36:16 +0300 | [diff] [blame] | 9 | public operator fun <T> invoke(block: () -> T): Try<T> = |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 10 | try { Success(block()) } catch(e: Throwable) { Failure<T>(e) } |
Roman Elizarov | dbcd841 | 2017-01-19 10:36:16 +0300 | [diff] [blame] | 11 | public fun <T> Success(value: T) = Try<T>(value) |
| 12 | public fun <T> Failure(exception: Throwable) = Try<T>(Fail(exception)) |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 13 | } |
| 14 | |
| 15 | @Suppress("UNCHECKED_CAST") |
| 16 | public val value: T get() = if (_value is Fail) throw _value.exception else _value as T |
| 17 | |
| 18 | public val exception: Throwable? get() = (_value as? Fail)?.exception |
| 19 | |
| 20 | override fun toString(): String = _value.toString() |
| 21 | } |