I have a gradle based project using Kotli DSL. The hierarchy is like the following.
root-project --> child-project
A function is defined in root project's build.gradle.kts file.
fun printHello() { println("Hello") }
I want to access this function in the child project's build.gradle.kts file. I tried calling the function but it says unresolved referenece printHello.
Whereas this is given in the gradle documentation that under the Dynamic methods sub heading https://docs.gradle.org/current/javadoc/org/gradle/api/Project.html *
A project has 5 method 'scopes', which it searches for methods:
- The methods of the parent project, recursively up to the root project.*
How can I achieve the same?
I have tried creating a function in root project's build.gradle.kts and invoking it in child project's build.gradle.kts file but it is saying unresolved reference printHello.
The documentation you link is written with a Groovy build script in mind. The approach when using the Kotlin DSL is a bit different because Kotlin is a statically typed language so the compiler must know what functions are defined at compile time.
The analogous way to access functions defined in a parent
build.gradle.ktsfile using Kotlin DSL would be (see partial documentation):None of these is type safe, however, and for that reason I would recommend writing a precompiled script plugin or a function inside the
src/main/kotlinfolder ofbuildSrcwith a Kotlin plugin applied in order to share a snippet of code between projects.