function - 为什么不能使用 'kotlin.Result' 作为返回类型?

我创建了一个方法,返回是Result<R>MyClass<R> 的类别中,但错误信息是:'kotlin.Result' 不能用作返回类型

我还查看了 Result 源代码以获取一些提示;为什么会这样?

Test code (使用 v. 1.3-RC)。

class MyClass<R>(val r: R) {
    fun f(): Result<R> { // error here
        return Result.success(r)
    }
}

fun main(args: Array<String>) {
    val s = Result.success(1)
    val m = MyClass(s)   
}

最佳答案

来自 Kotlin KEEP :

The rationale behind these limitations is that future versions of Kotlin may expand and/or change semantics of functions that return Result type and null-safety operators may change their semantics when used on values of Result type. In order to avoid breaking existing code in the future releases of Kotin and leave door open for those changes, the corresponding uses produce an error now. Exceptions to this rule are made for carefully-reviewed declarations in the standard library that are part of the Result type API itself.

注意:如果您只是想试验 Result 类型,您可以通过提供 Kotlin 编译器参数 -Xallow-result-return- 来绕过此限制输入

在 Java 或 Android 项目上使用 Gradle 时: 在 Kotlin 编译任务上定义编译器参数。它适用于生产代码和测试。

tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
    kotlinOptions {
        freeCompilerArgs = freeCompilerArgs + "-Xallow-result-return-type"
    }
}

在多平台项目上使用 Gradle 时: 为每个目标编译定义编译器参数。它适用于生产代码和测试。

kotlin {
    targets.all {
        compilations.all {
            kotlinOptions {
                freeCompilerArgs = freeCompilerArgs + "-Xallow-result-return-type"
            }
        }
    }
}

关于function - 为什么不能使用 'kotlin.Result' 作为返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52631827/

相关文章:

java - Kotlin 中的错误但仅使用 Java - 类 kotlin.reflect.jvm

android - JaCoCo 使用 Kotlin 和 Android 3.0 返回 0% 覆盖率

documentation - 如何在 kotlin kDoc 中使用 @link 和 @code

kotlin - Kotlin 中的静态方法导入

initialization - 为什么 Kotlin 不允许将 lateinit 与原始类型一起使

jpa - kotlin 数据类 + bean 验证 jsr 303

java - 在 Android Studio 中将 "java"目录重命名为 "kotlin"

java - 如何在 Intellij Idea 12 中重命名/移动项目?

android - ListAdapter 未更新 RecyclerView 中的项目

android - Kotlin 单例应用程序类