解决报错:The feature "nested type aliases" is experimental and should be enabled explicitly.
遇到的提示是:The feature "nested type aliases" is experimental and should be enabled explicitly. This can be done by supplying the compiler argument '-Xnested-type-aliases', but note that no stability guarantees are provided.
说明:nested type aliases(嵌套类型别名) 指的是:你可以在 Kotlin 的 class/对象体/接口内部为类型声明 typealias,而不是只在顶层声明。这是一个实验特性。
默认情况下 Kotlin 编译器不支持嵌套 typealias,如果你在类或接口里面写 typealias,会出现上述警告。
1、如何启用?
要启用“嵌套类型别名”,需要为 Kotlin 编译器补充参数:
-Xnested-type-aliases
2、Gradle 配置方法
针对 build.gradle.kts:
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs += listOf("-Xnested-type-aliases")
}
} 或者 Groovy DSL:
compileKotlin {
kotlinOptions {
freeCompilerArgs += "-Xnested-type-aliases"
}
}
3、注意事项
该特性非稳定,官方随时可能修改或移除,升级 Kotlin 时可能导致代码不兼容。
生产环境建议避免使用实验性特性,或仅在了解风险情况下使用。
4、示例
class MyClass {
typealias NameMap = Map<String, String>
// NameMap 只可在 MyClass 内部及其作用域使用
}
如果未开启该参数,编译时就会有文章开头的那个警告或异常。
精彩的人生需要浪漫、无畏和勇气。
这家伙太懒了,什么也没留下。