'Using "project.setProperty" vs a regular variable in Gradle Kotlin DSL?

What is the difference between these two approaches in a Gradle Kotlin build script?
Specifically, I wanted to know what is the advantage (if any) of using setProperty() method?

val myMainClass = "MainClass"

vs

setProperty("myMainClass", "MainClass") // equivalent to project.setProperty(...)


Solution 1:[1]

I wanted to know what is the advantage (if any) of using setProperty() method?

That is entirely dependent on your use case/what you're trying to achieve.

The first approach is not Gradle specific in any means. You are defining a read-only variable named myMainClass. This is just basic Kotlin: https://kotlinlang.org/docs/basic-syntax.html#variables

The second approach defining/setting a property on the current project. With this approach, wherever you have access to project, you can reference the property via property("myMainClass") or project.property("myMainClass")

setProperty and project.setProperty achieve the same outcome. In a Gradle build script, this refers to the project instance, which is why you can do setProperty, file, uri, ant, and so on.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cisco