The primary benefit of properties, as I understand it, is lazy configuration (if used correctly). They also let you define conventional values, even based on other providers, meaning the conventional value can be computed lazily as well. And there's also the benefit of the API provided by Property
. That includes methods like isPresent
and getOrElse
that let you handle an unset property with no conventional value. Note there are also more specialized types of properties, such as ListProperty
and DirectoryProperty
, which add more methods.
It's not that much more verbose to use properties, or at least it isn't anymore. You are injecting the object factory and creating the property manually. But you can just let Gradle create and decorate the extension (or task) class for you. It could look something like:
import org.gradle.api.provider.Property
abstract class ExamplePluginExtension {
abstract val exampleName: Property<String>
init {
// There's an overload that accepts a Provider. Note it might
// be better to do this in the plugin class after creating the
// extension, not sure).
exampleName.convention("default name")
}
}
Or as an interface:
import org.gradle.api.provider.Property
interface ExamplePluginExtension {
// If you want to set the conventional value, then you'd have to set it
// somewhere else (e.g., in the plugin class after creating the extension).
val exampleName: Property<String>
}
Then you'd register the extension:
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.*
class ExamplePlugin : Plugin<Project> {
override fun apply(project: Project) {
// this returns an instance of the extension class
project.extensions.create("example", ExamplePluginExtension::class)
}
}
Which would let you do the following in a build file:
plugins {
// apply example plugin
}
example {
exampleName = "Foo"
}