File: Try.kt

package info (click to toggle)
kotlinx-coroutines 1.0.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,628 kB
  • sloc: xml: 418; sh: 322; javascript: 60; makefile: 17; java: 8
file content (29 lines) | stat: -rw-r--r-- 980 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/*
 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

package kotlinx.coroutines

public class Try<out T> private constructor(private val _value: Any?) {
    private class Fail(val exception: Throwable) {
        override fun toString(): String = "Failure[$exception]"
    }

    public companion object {
        public operator fun <T> invoke(block: () -> T): Try<T> =
                try {
                    Success(block())
                } catch(e: Throwable) {
                    Failure<T>(e)
                }
        public fun <T> Success(value: T) = Try<T>(value)
        public fun <T> Failure(exception: Throwable) = Try<T>(Fail(exception))
    }

    @Suppress("UNCHECKED_CAST")
    public val value: T get() = if (_value is Fail) throw _value.exception else _value as T

    public val exception: Throwable? get() = (_value as? Fail)?.exception

    override fun toString(): String = _value.toString()
}