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