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

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

问题描述

我已经创建了一个方法,并且在MyClass<R>类中返回值为Result<R>,但是错误消息为'kotlin.Result'不能用作返回类型

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?

测试代码(使用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)   
}

推荐答案

来自科特琳KEEP :

这些限制背后的理由是,未来版本的 Kotlin可能会扩展和/或更改返回的函数的语义 结果类型和null安全运算符可能会在以下情况下更改其语义 用于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-type来绕过此限制.

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.

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

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