[英]Why can't 'kotlin.Result' be used as a return type?
我创建了一个方法,返回的是MyClass<R>
类中的Result<R>
,但错误信息是: 'kotlin.Result' cannot be used as a return type
我还查看了 Result 源代码以获得一些提示; 为什么会这样?
测试代码(使用 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 :
这些限制背后的基本原理是,Kotlin 的未来版本可能会扩展和/或更改返回 Result 类型的函数的语义,而 null 安全运算符在用于 Result 类型的值时可能会更改其语义。 为了避免在 Kotin 的未来版本中破坏现有代码并为这些更改敞开大门,相应的使用现在会产生错误。 此规则的例外是标准库中经过仔细审查的声明,这些声明是 Result 类型 API 本身的一部分。
注意:如果您只想试验Result
类型,您可以通过提供 Kotlin 编译器参数-Xallow-result-return-type
来绕过此限制。
在 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"
}
}
}
}
android {
kotlinOptions {
freeCompilerArgs = ["-Xallow-result-return-type"]
}
}
如果你使用android这个gradle这个解决方案
如果使用 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>
如果使用gradle:
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
kotlinOptions.freeCompilerArgs = ["-Xallow-result-return-type"]
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
kotlinOptions.freeCompilerArgs = ["-Xallow-result-return-type"]
}
资料来源: http : //rustyrazorblade.com/post/2018/2018-12-06-kotlin-result/
将 kotlin 版本更新到 1.5 或更高版本。 看:
https://github.com/Kotlin/KEEP/blob/master/proposals/stdlib/result.md#limitations-legacy
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.