在 Kotlin 中将 `Throwable?` 映射到 `Result<Unit>`

Mapping a `Throwable?` to a `Result<Unit>` in Kotlin

我想做的是将我的 Throwable? 映射到 Result.failureResult.success,具体取决于它的存在。

我认为这应该通过以下方式完成:

val a: Throwable? = Throwable()
val b = a?.let { Result.failure<Unit>(it) } ?: Result.success(Unit)

但是我得到的错误是:Expression of type kotlin.Result cannot be used as a left operand of '?:' 这似乎暗示我的 let 的结果是不可为 null 的。我不确定这怎么可能?我理解 let 类似于 map

Result 是一个实验性的 inline class 所以它有一些限制。目前,不允许在可空和非空结果类型上使用 Kotlin 空安全运算符 .??:!!。您可以在这里阅读更多相关信息:https://github.com/Kotlin/KEEP/blob/master/proposals/stdlib/result.md#limitations

我认为Result<T>不能作为Kotlin函数的直接结果类型,Result类型的属性也受到限制

来自 Result KEEP's future advancement

Kotlin nullable types have extensive support in Kotlin via operators ?., ?:, !!, and T? type constructor syntax. We can envision better integration of Result into the Kotlin language in the future. However, unlike nullable types, that are often used to represent non signalling failure that does not cary additional information, Result instances also carry additional information and, in general, shall be always handled in some way. Making Result an integral part of the language also requires a considerable effort on improving Kotlin type system to ensure proper handling of encapsulated exceptions.

你可以使用

val b: Result<Unit> = if (a != null) {
        Result.failure(a)
    } else {
        Result.success(Unit)
    }