如何解决在 Kotlin 中为依赖项块创建 Gradle 函数
目前,我正在创建一个函数,该函数可用于 Groovy 中的 dependencies
块:
project.dependencies.ext.foo = { String value ->
project.files(extension.getFooDependency(project).jarFiles).asFileTree
}
多亏了这一点,我才能做到:
afterEvaluate {
dependencies {
compileOnly foo('junit')
}
}
我正在将 Groovy 代码转换为 Kotlin,我想知道如何重写这个 foo
扩展。
我已经结束了:
project.dependencies.extensions.extraProperties.set("foo",Action { value: String ->
project.files(extension.getIdeaDependency(project).jarFiles).asFileTree
})
调用 foo('junit')
后,出现以下异常:
> Could not find method foo() for arguments [junit] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
解决方法
我认为这不会在 Kotlin DSL 中以相同的方式工作。相反,您可以在项目中的某处声明一个 Kotlin 扩展函数。然后调用它将包括所有必要的接收器。
对于多个项目,我建议使用 buildSrc
项目。下面的所有项目文件都可以看到那里的声明。
谈到对 Groovy 和 Kotlin 的支持,我会这样做:
private fun getFooImpl(scope: getFooImpl,name: String) { /*here is the implementation */ }
fun DependencyHandlerScope.getFoo(name:String) = getFooImpl(this,name)
//in Groovy
project.dependencies.extensions.extraProperties.set("foo",{getFooImpl(..)})
同样的代码也适用于插件。更通用的方法可能是注册一个 custom DLS extension,以便在 Gradle DSL 中允许自定义块状 thisIsMyPlugin { .. }
,并在扩展类中定义所有必要的辅助函数。这里的缺点是迫使用户将他们的代码包装到 thisIsMyPlugin
块中。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。