如何在Kotlin DSL中设置gradle的其他属性? [英] How are gradle extra properties set in the Kotlin DSL?
问题描述
我试图通过常规方式组织构建文件,方法是将值保存在单独的文件中以供重用.但是我不了解在Kotlin DSL中执行相同操作的语法.
I'm trying to organize my build files as I would in groovy, by having values in a separate file to reuse. But I cannot understand the syntax to do the same thing in the kotlin DSL.
这是我在root build.gradle.kts中使用的内容:
Here's what I'm using in root build.gradle.kts:
applyFrom("config.gradle.kts")
buildscript {
repositories {
google()
jcenter()
}
dependencies {
val test = project.extra["minSdkVer"]
classpath("com.android.tools.build:gradle:3.0.0-alpha4")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.1.2-5")
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
mavenCentral()
}
}
这是被引用的config.gradle.kts中的内容:
and here's whats in the config.gradle.kts that is being referenced:
mapOf(
Pair("minSdkVer", 22),
Pair("targetSdkVer", 25),
Pair("compiledSdkVer", 25),
Pair("buildToolsVer", "26-rc4")
).entries.forEach {
project.extra.set(it.key, it.value)
}
但是有一个错误:
无法通过额外的属性扩展获得属性'minSdkVer',因为它 不存在
Cannot get property 'minSdkVer' on extra properties extension as it does not exist
推荐答案
正确的解决方法: Gradle严格在执行脚本其他任何操作之前从脚本中收集并应用buildscript { ... }
块.因此,要使buildscript
中的config.gradle.kts
中的属性可用,您应将applyFrom("config.gradle.kts")
移到buildscript { ... }
块中:
A correct fix: Gradle collects and applies the buildscript { ... }
blocks from your script strictly before executing anything else from it. So, to make your properties from config.gradle.kts
available inside the buildscript
, you should move applyFrom("config.gradle.kts")
to your buildscript { ... }
block:
buildscript {
applyFrom("config.gradle.kts")
/* ... */
}
另一个可能的错误是在另一个ExtensionAware
范围内使用额外的属性作为extra["minSdkVer"]
,例如本例中的任务:
Another possible mistake is using an extra property as extra["minSdkVer"]
in a scope of another ExtensionAware
, like a task in this example:
val myTask = task("printMinSdkVer") {
doLast {
println("Extra property value: ${extra["minSdkVer"]}")
}
}
在这种情况下,extra.get(...)
不是使用任务的project.extra
,而是extra
.
In this case, extra.get(...)
uses not the project.extra
but the extra
of the task.
要解决此问题,请指定您使用该项目.直接使用:
To fix that, specify that you work with the project. Direct usage:
println(project.extra["minSdkVer"])
并授权.
val minSdkVer by project.extra
这篇关于如何在Kotlin DSL中设置gradle的其他属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!