Skip to content

Apps with Kotlin sources

The plugin works with apps written in Kotlin, but there are some pitfalls.

Gradle init generates a Kotlin app where the main method is a top-level function in an App.kt file. this works out of the box, but if the main method is part of a companion object, e.g., App.main it won’t be found by Jdeps or the run task, and the build fails.

Less magic means that some parts have to be a bit more explicit. If a method like main is part of the companion object, it needs the @JvmStatic annotation to become a “real” static class member.

org.example.App.kt
class App {
val greeting: String
get() {
return "Hello World!"
}
companion object {
@JvmStatic
fun main(vararg args: String) {
println(App().greeting)
}
}
}

There can be modularized projects that contain Kotlin sources. The build fails, because the Java compiler is unable to find the packages to export. The compiler needs the information where the packages and classes for that module can be found (module patching).

The Java plugin doesn’t offer a convenient way to declare module patches. But this plugin adds a patchModule source set extension where module patches can be defined and will be passed to the compiler. This is the more general solution compared to adding Kotlin-specific facilities to the plugin.

build.gradle.kts
sourceSets.named("main") {
patchModule.define {
module = application.mainModule
classes.from(kotlin.classesDirectory)
}
}

The inspiration came from this forum thread.