10

Basically I want to do exactly this:

Use Gradle function from other gradle file

which is to say, call one function in one gradle script from another. The wrinkle is that my build.gradle is in Kotlin (build.gradle.kts) and the script my function is in is still in groovy.

I followed the above link for groovy-to-groovy, but I can't get this to work using the Kotlin DSL.

In my groovy file, functions.gradle, I have:

def buildVersionName() {
        //Do some stuff
}

And

ext {
    buildVersionName = this.&buildVersionName
}

Then, in my build.gradle.kts script, I have:

apply(from = "functions.gradle")
project.ext.buildVersionName()

When I sync, I get the error:

Unresolved reference: buildVersionName
M Dapp
  • 1,453
  • 16
  • 31
  • Please add what you have tried and how it failed. – cfrick Jan 29 '20 at 18:25
  • I wondered how this can be done with Kotlin scripts alone and ended up using `buildSrc` (https://docs.gradle.org/current/userguide/organizing_gradle_projects.html). – Roland Jan 29 '20 at 19:13
  • Maybe the following will help you: https://guides.gradle.org/migrating-build-logic-from-groovy-to-kotlin/ (at the bottom there is a chapter about interoperability with Groovy (with a [link to another interoperability chapter speaking about accessing functions on a Groovy object](https://docs.gradle.org/current/userguide/kotlin_dsl.html#the_kotlin_dsl_groovy_builder))). – Roland Jan 29 '20 at 19:20

1 Answers1

7

In the build.gradle.kts do the following:

import groovy.lang.Closure
apply(from="functions.gradle")
val buildVersionName: Closure<Any> by ext
buildVersionName()
kaushik
  • 2,308
  • 6
  • 35
  • 50
  • @elect, `buildscript { repositories { maven { url = uri("https://plugins.gradle.org/m2/") } } apply(from = "https://raw.githubusercontent.com/i-net-software/SetupBuilder/master/scripts/SetupBuilderVersion.gradle") val setupBuilderVersion = project.extensions.extraProperties["setupBuilderVersion"] as groovy.lang.Closure<*> println(setupBuilderVersion()) }` – kaushik May 29 '20 at 14:48
  • https://stackoverflow.com/questions/62092938/calling-a-function-declared-in-a-third-part-gradle-file-from-within-the-buildscr – elect May 29 '20 at 18:57