You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gradle Kotlin-DSL中如何正确设置apiVersion与languageVersion?

问题描述

我在Gradle文件中使用如下声明:

plugins {
    `kotlin-dsl`
}

kotlin {
    compilerOptions {
        apiVersion.set("2.1")
        languageVersion.set("2.1")
    }
}

编译时出现如下错误:

* Where:
Build file '/home/peng/git/spookystuff/prover-commons/buildSrc/build.gradle.kts' line: 9

* What went wrong:
Script compilation errors:

  Line 09:         apiVersion.set("2.1")
                              ^ None of the following functions can be called with the arguments supplied: 
                                  public abstract fun set(provider: Provider<out KotlinVersion!>!): Unit defined in org.gradle.api.provider.Property
                                  public abstract fun set(value: KotlinVersion?): Unit defined in org.gradle.api.provider.Property

  Line 10:         languageVersion.set("2.1")
                                   ^ None of the following functions can be called with the arguments supplied: 
                                       public abstract fun set(provider: Provider<out KotlinVersion!>!): Unit defined in org.gradle.api.provider.Property
                                       public abstract fun set(value: KotlinVersion?): Unit defined in org.gradle.api.provider.Property

2 errors

由于KotlinVersion类未直接对我暴露,请问应如何正确设置这两个参数?

解决方案

你可以通过以下两种方式正确设置apiVersion和languageVersion:

方法1:使用全限定名调用KotlinVersion.valueOf

直接通过全限定类名获取KotlinVersion实例,无需额外导入:

plugins {
    `kotlin-dsl`
}

kotlin {
    compilerOptions {
        apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.valueOf("2.1"))
        languageVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.valueOf("2.1"))
    }
}

方法2:导入KotlinVersion类后使用

先导入对应的KotlinVersion类,再调用valueOf方法:

import org.jetbrains.kotlin.gradle.dsl.KotlinVersion

plugins {
    `kotlin-dsl`
}

kotlin {
    compilerOptions {
        apiVersion.set(KotlinVersion.valueOf("2.1"))
        languageVersion.set(KotlinVersion.valueOf("2.1"))
    }
}

这两种方式都能生成符合要求的KotlinVersion实例,解决编译报错问题。

内容的提问来源于stack exchange,提问作者tribbloid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 04:27:07