Kotlin, Groovy and Java Compilation

Looks like what you need is:

compileGroovy.dependsOn = compileGroovy.taskDependencies.values - 'compileJava'
compileKotlin.dependsOn compileGroovy
compileKotlin.classpath += files(compileGroovy.destinationDir)
classes.dependsOn compileKotlin
  • taskDependencies.values contains a String for the task name
  • You need an explicit dependency for the classes task, so it still runs before tests etc, because compileKotlin doesn’t output to the standard classes dir, it uses a post hook to copy from the kotlin-classes directory
  • Likewise, for Kotlin to compile against Groovy, you need to make the files output by the compileGroovy task visible, without using the sourceset output, as that’ll cause a circular dependency for classes

It means that interop can only go one way, Kotlin -> Groovy, so you need to use reflection at the seams, or move your key wiring classes to Kotlin.

Incidentally, this is a handy extension for Groovy Closure interop:

fun <T> T.groovyClosure(function: () -> Unit) = object : Closure<Unit>(this) {
    @Suppress("unused")
    fun doCall() {
        function()
    }
}
2 Likes