Categories
Gradle Java Kotlin Software

Gradle Build with Java 9 Modules and Kotlin

When starting a new Java project recently, I found it surprisingly difficult to setup the Gradle build with support for Java 9 modules and the Kotlin language.

For others who might find themselves in the same bind, here is a gist with the simplest, minimal gradle setup I came up with that includes:

  • A multi-project gradle build,
  • Java 9 modules support,
  • IntelliJ IDEA integration,
  • Kotlin language modules with support for cross-references between Java and Kotlin code in the same module.
plugins {
id 'idea'
id 'com.zyxist.chainsaw' version '0.3.1' apply false
id "org.jetbrains.kotlin.jvm" version "1.2.31" apply false
}
subprojects {
apply plugin: 'idea'
apply plugin: 'java-library'
apply plugin: 'com.zyxist.chainsaw'
}
// The idea plugin derives the JDK name as '1.9' while IDEA uses '9' as the default name for JDK 9
idea.project.jdkName = '9'

view raw
build.gradle
hosted with ❤ by GitHub

apply plugin: 'org.jetbrains.kotlin.jvm'
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib"
}
// Enable Kotlin compilation to Java 8 class files wiht method parameter name metadata
compileKotlin.kotlinOptions.jvmTarget = '1.8'
compileKotlin.kotlinOptions.javaParameters = true
// As per https://stackoverflow.com/a/47669720
// See also https://discuss.kotlinlang.org/t/kotlin-support-for-java-9-module-system/2499/9
compileKotlin.destinationDir = compileJava.destinationDir
jar.duplicatesStrategy = "exclude"
// Allow cross-references between java and kotlin
sourceSets.main.kotlin.srcDirs += 'src/main/java'

view raw
kotlin.gradle
hosted with ❤ by GitHub

Here is an proof-of-concept example of the above build scripts in action: https://github.com/nikolaybotevb/gradle-java9-kotlin.