I'm looking for a type-safe alternative to ext
in Gradle that allows me to define values accessible only within the subprojects of a specific parent project.
parent build.gradle.kts
:
subprojects {
ext["parentIntValue"] = 42
}
subproject build.gradle.kts
:
val parentIntValue: Int by project.extra // not type-safe
val localIntValue = parentIntValue
I know that buildSrc
provides type safety, but it applies to all subprojects starting from the root, whereas I need these values to have a more limited scope.
You can write a simple plugin to be applied in subprojects.
Add a build file to buildSrc
to build the plugin at buildSrc/build.gradle.kts
:
plugins {
`kotlin-dsl`
}
repositories {
mavenCentral()
}
Write your plugin at buildSrc/src/main/subprojectValues.gradle.kts
and use the extensions feature:
abstract class Values(
val someInt: Int
)
extensions.create<Values>("values", 42)
With the type embedded within this file, it is only available to build scripts which apply the plugin (ie not the parent project).
Apply the plugin in your subprojects within the parent build.gradle.kts
file:
subprojects {
apply(plugin = "subprojectValues")
}
(You could further generalise this approach by writing a further plugin which is applied in the parent build.gradle.kts
file which contains this code, giving you a simple reusable way of passing values to subprojects in multiple parent projects.)
Now the values are available in each subproject build.gradle.kts
:
println(values.someInt) // prints 42