Search code examples
kotlingradlegradle-kotlin-dsl

Can I write gradle buildSrc in Kotlin?


I'd like to write my Gradle buildSrc in Kotlin instead of Java, since everything else is Kotlin too.

I've tried .kt files in buildSrc/src/main/kotlin and in buildSrc/src/main/java, but neither will be compiled. IntelliJ does recognize them at least when I put them in /java, but they are not found when running Gradle tasks.

So, how do I make Gradle look at Kotlin build sources?


Solution

  • buildSrcis treated as an included build, and you can use any supported language inside this project, as long as you apply the needed plugins.

    Following setup should work :

    buildSrc/build.gradle

    plugins {
        id("org.jetbrains.kotlin.jvm") version "1.3.72"
    }
    repositories {
        mavenCentral()
    }
    

    custom task:

    buildSrc/src/main/kotlin/tasks/MyKtTask.kt

    package tasks
    
    import org.gradle.api.DefaultTask
    import org.gradle.api.tasks.TaskAction
    
    open class MyKtTask : DefaultTask() {
    
        @TaskAction
        fun execute() {
            println("kotlin tasks executed")
        }
    
    }
    

    Using the custom task:

    build.gradle

    task "testKt" (type: tasks.MyKtTask){
        doLast{
            // do something
        }
    }