blob: 546806680116a3c5a732cee6adfc68d01a83e390 [file] [log] [blame]
/*
* Copyright 2016-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlinx.coroutines.experimental
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()
}