添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

This is all part of trying to convert complicated Android build scripts from Groovy to Kotlin when I do not have a terribly great understanding of either language.

In Groovy, my top level build.gradle script had something like

ext {
    versionName = "2.2.11-35"
    versionCode = 2020211350

Different subprojects could reference this as
This is all part of trying to convert complicated Android build scripts from Groovy to Kotlin when I do not have a terribly great understanding of either language.

In Groovy, my top level build.gradle script had something like

ext {
    val versionName = "2.2.11-35"
    val versionCode = 2020211350

Which I could reference in the subproject build scripts as

        versionName = project.versionName
        versionCode = project.versionCode

When I try this in Kotlin, it complains that versionName and versionCode are undefined references. What is the correct way to implement this?

In Groovy you declare a local variable with def versionName = "2.2.11-35" which then is only available in that same build script.
In Kotlin you declare a local variable with val versionName = "2.2.11-35" which then is only availabel in that same build script, or within the scope it is declared actually, so just within that ext { ... } block.

The equivalent of

ext {
    versionName = "2.2.11-35"
    versionCode = 2020211350

would be

val versionName by extra("2.2.11-35")
val versionCode by extra(2020211350)

and access should be

val versionName: String by extra
val versionCode: Int by extra

Be aware though, that practically any usage of ext or extra properties (independent of DSL language) is usually a work-around for doing something not properly.

For example you could put those values into gradle.properties file and then just access it from all projects, or as they are versions maybe even better put them into the version catalog, then you can also type-safely access them e.g. using libs.versions.versionName.get() or libs.versions.versionCode.get().toInt(). or if what you set from it properly handles Provider then even without get()ing the providers.