为什么'kotlin.Result'不能用作返回类型

ers*_*tan 47 function return-type kotlin

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

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

测试代码(使用v.1.3-RC):https://try.kotlinlang.org/#/UserProjects/ueeogpr0cqnovot7o4ooa42dv5/l9qidpqj9pf1i7rablka4u5qjt

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)   
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*kov 38

来自Kotlin KEEP:

这些限制背后的基本原理是,未来版本的Kotlin可能会扩展和/或更改返回Result类型的函数的语义,而null安全运算符在使用Result类型的值时可能会更改其语义.为了避免在Kotin的未来版本中破坏现有代码并为这些更改保持打开状态,相应的用法现在会产生错误.此规则的例外情况是针对标准库中经过仔细审阅的声明而生成的,这些声明是Result类型API本身的一部分.

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

  • 你能添加一个关于如何在gradle中完成的片段吗? (2认同)

小智 10

android {
    kotlinOptions {
        freeCompilerArgs = ["-Xallow-result-return-type"]
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您使用android此解决方案


Cal*_*lin 9

如果使用 Maven:

<plugin>
    <artifactId>kotlin-maven-plugin</artifactId>
    <configuration>
        <jvmTarget>1.8</jvmTarget>
        <args>
            <arg>-Xallow-result-return-type</arg>
        </args>
    </configuration>
    <groupId>org.jetbrains.kotlin</groupId>
    <version>${kotlin.version}</version>
Run Code Online (Sandbox Code Playgroud)

如果使用gradle:

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
    kotlinOptions.freeCompilerArgs = ["-Xallow-result-return-type"]


}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
    kotlinOptions.freeCompilerArgs = ["-Xallow-result-return-type"]
}
Run Code Online (Sandbox Code Playgroud)

来源:http : //rustyrazorblade.com/post/2018/2018-12-06-kotlin-result/