How to set up Kotlin's byte code version in Gradle project to Java 8?

前端 未结 9 1778
挽巷
挽巷 2020-12-01 08:56

In Kotlin project, what is a proper Gradle script to make sure my classes will be compiled to byte code ver 52 (Java 8)?

For some reason my classes are compiled as v

相关标签:
9条回答
  • 2020-12-01 09:20

    As Mark pointed out on Debop's answer, you have to configure both compileKotlin and compileTestKotlin. You can do it without duplication this way:

    tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
      kotlinOptions {
        jvmTarget = "1.8"
      }
    }
    

    For a pure Kotlin project, I don't think the options sourceCompatibility and targetCompatibility do anything, so you may be able to remove them.

    Ref: https://kotlinlang.org/docs/reference/using-gradle.html#compiler-options

    0 讨论(0)
  • 2020-12-01 09:22

    For anyone like me who use maven to build mixed code of kotlin and java in intellij , you need to set

    <kotlin.compiler.jvmTarget>1.8</kotlin.compiler.jvmTarget>
    

    because maven build doesn't respect jvmTarget set in project setting.

    0 讨论(0)
  • 2020-12-01 09:27

    If you're getting an error like this: Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6. Please specify proper '-jvm-target' option.

    Then, you can simply add the following in build.gradle (in Groovy) in order to tell kotlin to build using 1.8.

    compileKotlin {
        kotlinOptions {
            jvmTarget = "1.8"
        }
    }
    
    0 讨论(0)
  • 2020-12-01 09:33
    import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
    
    // JVM target applied to all Kotlin tasks across all subprojects
    
    // Kotlin DSL
    tasks.withType<KotlinCompile> {
        kotlinOptions.jvmTarget = JavaVersion.VERSION_1_8.toString()
    }
    
    //Groovy
    tasks.withType(KotlinCompile) {
        kotlinOptions.jvmTarget = JavaVersion.VERSION_1_8
    }
    
    0 讨论(0)
  • 2020-12-01 09:34

    Kotlin 1.1 in Gradle. in console you have error about inline (your installed compiler is 1.0.x) If run gradle task in IntelliJ IDEA, your code compiled by kotlin 1.1 compiler

    compileKotlin {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    
        kotlinOptions {
            jvmTarget = "1.8"
            apiVersion = "1.1"
            languageVersion = "1.1"
        }
    }
    
    0 讨论(0)
  • 2020-12-01 09:36

    In case someone uses gradle with kotlin-dsl instead of groovy:

    import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
    
    // compile bytecode to java 8 (default is java 6)
    tasks.withType<KotlinCompile> {
        kotlinOptions.jvmTarget = "1.8"
    }
    
    0 讨论(0)
提交回复
热议问题