Reuse gradle.kts function

Viewed 1872

I have a multiproject gradle.kts setup and I would like to reuse a function, eg.

fun doSomethingWithString(string: String) { return string }

I then use the function within the dependencies {} block.

I would like to either:

  • define the fun within the root build.gradle.kts
  • define the fun within some other file which I could import within every subproject

Is this feasible?

1 Answers

You can create your function in a buildSrc project.

There are various ways to approach this. Here are just two examples for how this could be done. Both use the same buildSrc/build.gradle.kts:

plugins {
    `kotlin-dsl`
}

repositories {
    jcenter()
}

Example: Shared Package-Level Function

You can create a package-level function, e.g., in buildSrc/src/main/kotlin/myconvention/myconventions.kt:

package myconvention

fun doSomethingWithString(string: String): String {
  return string + "321"
}

Then in your (sub)project build scripts, you can access the function as follows:

println(myconvention.doSomethingWithString("foo"))

Example: Precompiled Script Plugin

You can create the function as an extra property on the project in a precompiled script plugin, e.g., if you have buildSrc/src/main/kotlin/myproject.conventions.gradle.kts:

val doSomethingWithString by extra(
  fun(string: String): String {
    return string + "123"
  }
)

Then in your (sub)project build scripts, you can access the function as follows:

plugins {
    id("myproject.conventions")
}
val doSomethingWithString: (String) -> String by extra

println(doSomethingWithString("foo"))

Minimal Working Configuration for the First Example

Complete root project directory structure (excl. Gradle Wrapper files):

├── mysub
│   └── build.gradle.kts
├── buildSrc
│   ├── build.gradle.kts
│   └── src
│       └── main
│           └── kotlin
│               └── myconvention
│                   └── myconventions.kt
└── settings.gradle.kts
  • mysub/build.gradle.kts only contains println(myconvention.doSomethingWithString("foo"))
  • buildSrc/build.gradle.kts and buildSrc/src/main/kotlin/myconvention/myconventions.kt have the exact content described above
  • settings.gradle.kts:
rootProject.name = "my_test"
include("mysub")

When running ./gradlew projects (using Gradle 6.7.1), the output contains the following, as expected:

> Configure project :mysub
foo321
Related