如何将 KotlinPoet 依赖项添加到简单的控制台应用程序?

How to add KotlinPoet dependency to simple console app?

我正在编写一个简单的控制台应用程序,它应该在执行时生成一些 kotlin 代码。我遇到了一个奇怪的问题,我无法添加 KotlinPoen 依赖项。我的 build.gradle:

plugins {
    id 'java-library'
    id 'kotlin'
}

java {
    sourceCompatibility = JavaVersion.VERSION_1_7
    targetCompatibility = JavaVersion.VERSION_1_7
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation group: 'com.squareup', name: 'kotlinpoet', version: '1.7.2'
}

但在 PoetApp.kt 中导入失败并显示消息 Unresolved reference: squareup:

import com.squareup.kotlinpoet.FunSpec

object PoetApp {

    @JvmStatic
    fun main(vararg param: String) {
        val main = FunSpec.builder("main")
            .addCode("""
        |var total = 0
        |for (i in 0 until 10) {
        |    total += i
        |}
        |""".trimMargin())
            .build()
    }

}

您已声明 Java 与 1.7 版兼容,但此版本的 kotlinpoet 仅适用于 1.8 及更高版本,请参阅 library gradle file and also some compatibility issue solved here

所以你的 build.gradle 应该是这样的:

plugins {
    id 'java-library'
    id 'kotlin'
}

java {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation group: 'com.squareup', name: 'kotlinpoet', version: '1.7.2'
}