mirror of
https://github.com/jlengrand/kotlin.git
synced 2026-05-16 15:53:55 +00:00
* The members of Result are isSuccess, isFailure, exceptionOrNull, getOrNull * The rest of API is implemented via inline-only extensions * There are two internal functions to hide detailed mechanics of an internal Result.Failure class: createFailure and throwOnFailure * Result.toString is explicit: either Success(v) or Failure(x) See KT-26538
36 lines
848 B
Kotlin
Vendored
36 lines
848 B
Kotlin
Vendored
// !LANGUAGE: +InlineClasses
|
|
// IGNORE_BACKEND: JVM_IR
|
|
|
|
inline class Result<out T>(val value: Any?) {
|
|
val isFailure: Boolean get() = value is Failure
|
|
|
|
public companion object {
|
|
public inline fun <T> success(value: T): Result<T> =
|
|
Result(value)
|
|
|
|
public inline fun <T> failure(exception: Throwable): Result<T> =
|
|
Result(Failure(exception))
|
|
}
|
|
|
|
class Failure (
|
|
val exception: Throwable
|
|
)
|
|
}
|
|
|
|
inline fun <R> runCatching(block: () -> R): Result<R> {
|
|
return try {
|
|
Result.success(block())
|
|
} catch (e: Throwable) {
|
|
Result.failure(e)
|
|
}
|
|
}
|
|
|
|
class Box<T>(val x: T)
|
|
|
|
fun box(): String {
|
|
val r = runCatching { TODO() }
|
|
val b = Box(r)
|
|
if (r.isFailure != b.x.isFailure || !r.isFailure) return "Fail: r=${r.isFailure}; b.x=${b.x.isFailure}"
|
|
|
|
return "OK"
|
|
} |