Kotlin-runCatching

runCatching 源码

/**
 * Calls the specified function [block] with `this` value as its receiver and returns its encapsulated result if invocation was successful,
 * catching any [Throwable] exception that was thrown from the [block] function execution and encapsulating it as a failure.
 */
@InlineOnly
@SinceKotlin("1.3")
public inline fun <T, R> T.runCatching(block: T.() -> R): Result<R> {
    return try {
        Result.success(block())
    } catch (e: Throwable) {
        Result.failure(e)
    }
}

runCatching 函数返回的是一个 Result 类,Result 类中,一共定义了如上述的 4 个方法:

  • 其中 getOrNull 返回的是 runCatching 中处理的结果,是一个可空类型的。
  • getOrDefault 返回的是一个不可空的类型,调用的时候需要传递默认值,为 null 的时候会返回默认值。
  • getOrThrow 未发生的异常返回的是 runCatching 中处理的结果,如果 runCatching 中发生了异常,调用这个 API 会抛出异常。
  • getOrElse 返回处理的结果,或者是异常自己处理。
1.runCatching 的实现

runCatching 是一个内联的高阶函数,返回了一个 Result 类,函数里面对回调出去的 lambda 表达式进行了 try catch 的处理。返回的内容使用 Result.success 和 Result.failure 进行的包裹

2.getOrNull
@InlineOnly
public inline fun getOrNull(): T? =
       when {
            isFailure -> null
            else -> value as T
       }
}

异常的情况返回 null ,要么就是返回 value, value 是 Result 的一个属性,也就是上面使用 Result.success(block()) 中返回的结果

3.getOrDefault
public inline fun <R, T : R> Result<T>.getOrDefault(defaultValue: R): R {
    if (isFailure) return defaultValue
    return value as T
}

如果是异常的情况返回默认值,要么返回的是 value

4.getOrElse
public inline fun <R, T : R> Result<T>.getOrElse(onFailure: (exception: Throwable) -> R): R {
    contract {
        callsInPlace(onFailure, InvocationKind.AT_MOST_ONCE)
    }
    return when (val exception = exceptionOrNull()) {
        null -> value as T
        else -> onFailure(exception)
    }
}

先看看 exceptionOrNull 处理的是什么:

public fun exceptionOrNull(): Throwable? =
        when (value) {
            is Failure -> value.exception
            else -> null
        }

exceptionOrNull 返回的是: 如果是发生了异常返回异常类, 否则返回 null, 所以 getOrElse 里面返回的是: 异常情况下,返回异常类,否则返回处理的结果 value

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容