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:
fun
within the root build.gradle.kts
fun
within some other file which I could import within every subprojectIs this feasible?
KTS: Refers to Kotlin script, a flavor of the Kotlin language used by Gradle in build configuration files. Kotlin script is Kotlin code that can be run from the command line. Kotlin DSL: Refers primarily to the Android Gradle plugin Kotlin DSL or, occasionally, to the underlying Gradle Kotlin DSL.
buildSrc is a separate build whose purpose is to build any tasks, plugins, or other classes which are intended to be used in build scripts of the main build, but don't have to be shared across builds.
buildscript: This block is used to configure the repositories and dependencies for Gradle. dependencies: This block in buildscript is used to configure dependencies that the Gradle needs to build during the project.
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()
}
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"))
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"))
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 abovesettings.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With