为什么不能将“kotlin.Result"用作返回类型? [英] Why can't 'kotlin.Result' be used as a return type?

查看:51
本文介绍了为什么不能将“kotlin.Result"用作返回类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个方法,在MyClass的类中返回的是Result,但是错误信息是:'kotlin.结果'不能用作返回类型

I've created a method, and the return is Result<R> in a class of MyClass<R>, but the error message is: 'kotlin.Result' cannot be used as a return type

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

I've also looked into the Result source code for some hints; why is this so?

测试代码(使用 v. 1.3-RC).

Test code (using 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 保持:

这些限制背后的基本原理是未来版本的Kotlin 可能会扩展和/或更改返回函数的语义结果类型和空安全运算符可能会在以下情况下更改其语义用于 Result 类型的值.为了避免破坏现有的在 Kotin 的未来版本中编写代码,并为那些人敞开大门更改,相应的用途现在会产生错误.例外情况本规则是为仔细审查标准中的声明而制定的属于 Result 类型 API 本身的库.

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- 来绕过此限制输入.

Note: if you just want to experiment with the Result type you can bypass this limitation by supplying a Kotlin compiler argument -Xallow-result-return-type.

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

When using Gradle on Java or Android project: Define the compiler argument on Kotlin compilation task. It applies both for production code and tests.

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

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

When using Gradle on Multiplatform project: Define the compiler argument for each target compilation. It applies both for production code and tests.

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

这篇关于为什么不能将“kotlin.Result"用作返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆