首页 > 解决方案 > Kotlin 编译在终端中失败,但不是 Intellij

问题描述

我在一个类中有以下导入:

import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse

当我在 Intellij 内部构建时,依赖关系得到了正确解决并且没有问题。当我在 GitHub Actions 中运行 CI 时,也没有任何问题。

但是,当我在我的 macOS 终端中运行 ./gradlew clean build 时,它无法解析上述依赖项。它在 compileKotlin 步骤中失败。

以下是我的 build.gradle 文件。

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

group 'com.test'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()

}

dependencies {

    // kotlin
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"

    // gson
    implementation 'com.google.code.gson:gson:2.8.6'

    // testing
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.3.1'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.3.1'
    testRuntime('org.junit.jupiter:junit-jupiter-engine:5.4.2')
    testCompile("org.assertj:assertj-core:3.11.1")
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

test {
    useJUnitPlatform()
}


谢谢!

标签: gradleintellij-ideakotlincompiler-errors

解决方案


java.net.httpAPI 是在 JDK 11 中引入的。从终端运行 Gradle 构建时出现未解决的引用错误的原因很可能是那里使用的 JDK 的较低版本。

默认情况下,compileKotlin任务使用与用于启动 Gradle 构建本身的 JDK 相同的 JDK。

Gradle 通过JAVA_HOME环境变量或java在 PATH 中查找命令来检测 JDK 的路径。因此,为 Gradle 指定 JDK 最可靠的方法是将JAVA_HOME终端中的环境变量设置为所需的 JDK 路径。

或者,compileKotlin任务可以使用不同于 Gradle 中默认的 JDK。因此,例如,即使 Gradle 与 JDK 8 一起运行,它也可以为 JDK 11 编译。这是使用jdkHome编译器选项设置的:

compileKotlin {
    kotlinOptions.jdkHome = "path_to_jdk_here"
}

在此处查看 Kotlin/JVM 编译任务的其他选项:https ://kotlinlang.org/docs/reference/using-gradle.html#attributes-specific-for-jvm


推荐阅读