Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to target JVM 9 on Kotlin with Gradle?

Tags:

gradle

kotlin

Targeting JVM 1.8 on Kotlin with Gradle is as easy as

compileKotlin {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

But that doesn't work for Java 9 if I simply change the jvmTarget to 9 or 1.9. How can I do it?

like image 610
MrPNG Avatar asked Nov 12 '17 13:11

MrPNG


People also ask

Which JVM for Kotlin?

Which versions of JVM does Kotlin target? Kotlin lets you choose the version of JVM for execution. By default, the Kotlin/JVM compiler produces Java 8 compatible bytecode. If you want to make use of optimizations available in newer versions of Java, you can explicitly specify the target Java version from 9 to 18.

Does gradle work with Kotlin?

Gradle is a build system that is very commonly used in the Java, Android, and other ecosystems. It is the default choice for Kotlin/Native and Multiplatform when it comes to build systems.

Does Kotlin compile to JVM?

The Kotlin compiler for JVM compiles Kotlin source files into Java class files. The command-line tools for Kotlin to JVM compilation are kotlinc and kotlinc-jvm . You can also use them for executing Kotlin script files.


1 Answers

Kotlin currently only targets Java 6 and 8

See the FAQs here https://kotlinlang.org/docs/reference/faq.html#does-kotlin-only-target-java-6

Which at the moment says

Does Kotlin only target Java 6? No. Kotlin lets you choose between generating Java 6 and Java 8 compatible bytecode. More optimal byte code may be generated for higher versions of the platform.


edit:

So... because it's the compatibility of the bytecode that kotlin is generating it doesn't mean that fixes the Java version you need to use.

Here's a gradle file that let's you use Java 11 alongside kotlin generating Java 8 compatible bytecode

plugins {
    id 'java'
    id 'org.jetbrains.kotlin.jvm' version '1.2.71'
}

group 'com.dambra.paul.string-calculator'
version '0.0.0'

sourceCompatibility = 11.0

repositories {
    mavenCentral()
}

dependencies {
    testImplementation(
            'org.junit.jupiter:junit-jupiter-api:5.1.0'
    )
    testRuntimeOnly(
            'org.junit.jupiter:junit-jupiter-engine:5.1.0'
    )
    testCompile("org.assertj:assertj-core:3.11.1")
    testCompile 'org.junit.jupiter:junit-jupiter-params:5.1.0'
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
}
compileKotlin {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}
compileTestKotlin {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

You can't "target jvm 9" with Kotlin. But you can write Kotlin alongside Java (9|10|11|etc)

like image 175
Paul D'Ambra Avatar answered Sep 22 '22 12:09

Paul D'Ambra