I'm migrating Gradle build scripts from Groovy to Kotlin DSL and one of the things which is not really documented is how to populate extra properties.

In Groovy, I can write:

ext {
    comp = 'node_exporter'
    compVersion = '0.16.0'
    compProject = 'prometheus'
    arch = 'linux-amd64'
    tarball = "v${compVersion}/${comp}-${compVersion}.${arch}.tar.gz"
    downloadSrc = "https://github.com/${compProject}/${comp}/releases/download/${tarball}"
    unzipDir = "${comp}-${compVersion}.${arch}"
}

我发现在Kotlin DSL中,我可以通过以下方式实现相同的功能:

val comp by extra { "filebeat" }
val compVersion by extra { "6.4.0" }
val arch by extra { "linux-x86_64" }
val tarball by extra { "${comp}-${compVersion}-${arch}.tar.gz" }
val downloadSrc by extra { "https://artifacts.elastic.co/downloads/beats/${comp}/${tarball}" }
val unzipDir by extra { "${comp}-${compVersion}-${arch}" }

which looks pretty repetitive.

Implementation of ExtraPropertiesExtension in Kotlin is a little bit complex, but at the end, it holds just plain old Map<String, Object>.

那么,我的问题是:is it possible to populate 100 object with multiple properties more easily, than just repeating 101?

推荐答案

根据当前(5.2.1)份文件:

All enhanced objects in Gradle’s domain model can hold extra user-defined properties. This includes, but is not limited to, projects, tasks, and source sets.

Extra properties can be added, read and set via the owning object’s extra property. Alternatively, they can be addressed via Kotlin delegated properties using by extra.

Here is an example of using extra properties on the Project and Task objects:

val kotlinVersion by extra { "1.3.21" }
val kotlinDslVersion by extra("1.1.3")
extra["isKotlinDsl"] = true

tasks.register("printExtProps") {
    extra["kotlinPositive"] = true

    doLast {
        // Extra properties defined on the Project object
        println("Kotlin version: $kotlinVersion")
        println("Kotlin DSL version: $kotlinDslVersion")
        println("Is Kotlin DSL: ${project.extra["isKotlinDsl"]}")
        // Extra properties defined on the Task object
        // this means the current Task
        println("Kotlin positive: ${this.extra["kotlinPositive"]}")
    }
}

Kotlin相关问答推荐

Kotlin -从列表中获取特定过滤器的唯一列表值

创建包含 3 个相同项目的列表/使用返回类型重复

Kotlin Path.useLines { } - 如何不获取 IOException("Stream closed")?

为什么这个 Kotlin 代码不起作用? (如果 str[index] 在列表中,则打印)

Jetpack Compose - 单击 LazyColumn 的项目时应用程序崩溃

即使 Kotlin 的 `Map` 不是 `Iterable`,它如何以及为什么是可迭代的?

Kotlin 方法重载

如何从不同的功能发出流量值? Kotlin 协程

Kotlin 中 lambda 表达式中的默认参数

Kotlin 的 isNullOrBlank() 函数是否可以导入 xml 以用于数据绑定

Intellij 显示 build.gradle.kts 中的每一行都是红色的

哪里可以找到aapt2日志(log)?

requireNotNull vs sure !! 操作符

如何在使用 Gradle 的 AppEngine 项目中使用 Kotlin

Kotlin惰性默认属性

如何在Kotlin中获得KType?

Lint 错误:可疑的相等判断:在 Object DiffUtilEquals 中未实现 equals()

查找是否在列表中找到具有特定属性值的元素

Android Kotlin .visibility

Kotlin:访问 when 语句的参数