如何使用Java 9/10和Gradle的Kotlin DSL构建Gradle Kotlin项目?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (614)

有一个具有以下结构的gradle项目(这里只有相关内容):

src/
|   main/
|   |   kotlin/
|   |   |   com/example/testproject/
|   |   |   |   Main.kt
|   |   |   module-info.java
build.gradle.kts
settings.gradle

通常我会在其上运行gradle run,但会导致以下错误:

module-info.java:3: error: module not found: kotlin.stdlib
  requires kotlin.stdlib;

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

buildscript {
  var kotlin_version: String by extra
  kotlin_version = "1.2.41"

  repositories {
    mavenCentral()
  }
  dependencies {
    classpath(kotlin("gradle-plugin", kotlin_version))
  }
}

repositories {
  mavenCentral()
}

plugins {
  kotlin("jvm") version "1.2.41"
  application
}

val kotlin_version: String by extra

dependencies {
  implementation(kotlin("stdlib", kotlin_version))
  implementation(kotlin("stdlib-jdk8", kotlin_version))
  implementation(kotlin("runtime", kotlin_version))
  implementation(kotlin("reflect", kotlin_version))
}

val group = "com.example"
application {
  mainClassName = "$group.testproject.Main"
}

java {
  sourceCompatibility = JavaVersion.VERSION_1_10
  targetCompatibility = sourceCompatibility
  sourceSets {
    "main" {
      java.srcDirs("src/main/kotlin")
    }
  }
}

tasks.withType<KotlinCompile> {
  kotlinOptions.jvmTarget = "1.8"
}

module-info.java:

module com.example.testproject {
  // Kotlin compatibility
  requires kotlin.stdlib;
  exports com.example.testproject;
}
提问于
用户回答回答于

我遇到的第一个问题是在Kotlin函数中有两个冲突的提供者:

  implementation(kotlin("stdlib", kotlin_version))
  implementation(kotlin("runtime", kotlin_version))

compileJava任务没有找到正确的类(来自项目)和模块(来自分发)。因此,我需要调整路径,如下例所示:

val compileKotlin: KotlinCompile by tasks
val compileJava: JavaCompile by tasks
compileJava.destinationDir = compileKotlin.destinationDir

可以通过以下非惯用的Kotlin脚本来解决:

tasks {
  "compileJava" {
    dependsOn(":compileKotlin")
    if (JavaVersion.current() >= JavaVersion.VERSION_1_9) {
      inputs.property("moduleName", ext["moduleName"])
      doFirst {
        compileJava.options.compilerArgs = listOf(
            // include Gradle dependencies as modules
            "--module-path", java.sourceSets["main"].compileClasspath.asPath,
        )
        java.sourceSets["main"].compileClasspath = files()
      }
    }
  }
}

扫码关注云+社区

领取腾讯云代金券