Search code examples
spring-bootgradlegradle-kotlin-dslgradlewdynamicmethod

How to access a function in child project's build.gradle.kts which is defined in root project's build.gradle.kts


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.


Solution

  • 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.kts file using Kotlin DSL would be (see partial documentation):

    // In root build.gradle.kts
    
    // Option 1: Double braces as the return value of the outer lambda gives the property value
    val printHello by extra { { println("Hello") } }
    
    // Option 2
    extra["printHello"] = { println("Hello") }
    
    // In child build.gradle.kts
    
    // Option 1
    val printHello: () -> Unit by project
    printHello()
    
    // Option 2
    (rootProject.extra["printHello"] as () -> Unit)()
    

    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/kotlin folder of buildSrc with a Kotlin plugin applied in order to share a snippet of code between projects.