我可以看到 Ktor 1.4.X,例如io.ktor.config.ApplicationConfig
被标记为 @KtorExperimentalAPI
,因此任何调用它的东西也需要被标记为 @KtorExperimentalAPI
。
编辑添加:在 Ktor 1.5.0 中,io.ktor.config.ApplicationConfig
不再需要 @KtorExperimentalAPI
,因此目前最好的解决方法是升级 Ktor 版本。< /p>
但这在本质上是传播的。如果我实现了一个实用程序函数,它需要一个应用程序配置参数,因此调用实验性的 Application.environment.config.property(path)
API,这个实用程序函数也必须标记为 @KtorExperimentalAPI
。林斯,重复一遍。很快,我的应用程序中的所有内容都标记为 @KtorExperimentalAPI
,因为在实现中的某处(调用 API)* 调用实验性 API。
有什么方法可以“封装坏处”:调用实验性 API 并在那里做一些魔术,这样 @KtorExperimentalAPI
就不会变得像病毒一样传播到应用程序的其余部分?
例如:
// I can accept that this perhaps
// needs to be marked @KtorExperimentalAPI
@KtorExperimentalAPI
fun Application.configProperty(path: String) : String {
return environment.config.property(path).getString()
}
// But I want to avoid that everything that calls it also
// needs to be marked @KtorExperimentalAPI
fun Application.getFoobarProperty() : String {
return "${configProperty("foo")}_${configProperty("bar")}";
}
答案 0 :(得分:2)
您可以使用编译器参数将选择加入配置为模块范围内。有了这个编译器参数,您就不必再使用注释了。您可以在此处阅读更多相关信息:https://kotlinlang.org/docs/reference/opt-in-requirements.html#module-wide-opt-in
如果您使用的是 Kotlin-Gradle,请将其添加到您的编译任务中:
kotlinOptions.freeCompilerArgs += "-Xopt-in=io.ktor.util.KtorExperimentalAPI"
如果您使用的是 Maven,请将此配置添加到 kotlin-maven-plugin
:
<configuration>
<args>
<arg>-Xopt-in=io.ktor.util.KtorExperimentalAPI</arg>
</args>
</configuration>
答案 1 :(得分:0)
感谢@marstran 的回答中提供的链接,我找到了我要找的东西:
https://kotlinlang.org/docs/reference/opt-in-requirements.html#non-propagating-use
它描述了如何做我想做的事:
<块引用>在不公开自己的 API 的模块(例如应用程序)中,您可以选择使用 API,而无需将选择使用要求传播到您的代码。在这种情况下,使用@OptIn 标记您的声明,将选择加入要求注释作为其参数
我最终得到:
main
确实需要将此添加到// Not @KtorExperimentalAPI, but:
@OptIn(KtorExperimentalAPI::class)
fun Application.configProperty(path: String) : String {
return environment.config.property(path).getString()
}
:
build.gradle.kts