Roman Elizarov | f16fd27 | 2017-02-07 11:26:00 +0300 | [diff] [blame] | 1 | /* |
Roman Elizarov | 1f74a2d | 2018-06-29 19:19:45 +0300 | [diff] [blame^] | 2 | * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
Roman Elizarov | f16fd27 | 2017-02-07 11:26:00 +0300 | [diff] [blame] | 3 | */ |
| 4 | |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 5 | package kotlinx.coroutines.experimental |
| 6 | |
Roman Elizarov | dbcd841 | 2017-01-19 10:36:16 +0300 | [diff] [blame] | 7 | public class Try<out T> private constructor(private val _value: Any?) { |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 8 | private class Fail(val exception: Throwable) { |
| 9 | override fun toString(): String = "Failure[$exception]" |
| 10 | } |
| 11 | |
| 12 | public companion object { |
Roman Elizarov | dbcd841 | 2017-01-19 10:36:16 +0300 | [diff] [blame] | 13 | public operator fun <T> invoke(block: () -> T): Try<T> = |
Roman Elizarov | 9d5abcd | 2017-12-21 16:54:30 +0300 | [diff] [blame] | 14 | try { |
| 15 | Success(block()) |
| 16 | } catch(e: Throwable) { |
| 17 | Failure<T>(e) |
| 18 | } |
Roman Elizarov | dbcd841 | 2017-01-19 10:36:16 +0300 | [diff] [blame] | 19 | public fun <T> Success(value: T) = Try<T>(value) |
| 20 | public fun <T> Failure(exception: Throwable) = Try<T>(Fail(exception)) |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 21 | } |
| 22 | |
| 23 | @Suppress("UNCHECKED_CAST") |
| 24 | public val value: T get() = if (_value is Fail) throw _value.exception else _value as T |
| 25 | |
| 26 | public val exception: Throwable? get() = (_value as? Fail)?.exception |
| 27 | |
| 28 | override fun toString(): String = _value.toString() |
| 29 | } |