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

IntelliJ与Gradle项目中Kotlin委托行为差异原因咨询

Kotlin委托在IntelliJ与Gradle项目中行为差异的原因

环境与测试场景

我的IntelliJ版本为2024.2.4(Build #IU-242.23726.103,构建于2024年10月23日),分别在两种项目中创建了相同的Kotlin委托代码:

  • IntelliJ项目:通过File > New > Project... > Kotlin创建,构建系统为IntelliJ,使用OpenJdk 23
  • Gradle项目:通过相同路径创建,构建系统为Gradle,使用OpenJdk 23与Kotlin

测试代码

interface Base {
    fun printMessage()
}

class BaseImpl(val x: Int) : Base {
    override fun printMessage() { println(x) }
}

class BaseImpl2(val x: Int) : Base {
    override fun printMessage() { println("2 $x") }
}

class Derived(var b: Base) : Base by b {

}

fun main() {
    val base1 = BaseImpl(10)
    val base2 = BaseImpl(12)
    val derived = Derived(base1)
    derived.printMessage()
    derived.b = base2
    derived.printMessage()
}

执行结果

IntelliJ项目输出

10
12

Gradle项目输出

10
10

差异细节与补充信息

  • 字节码差异:Gradle项目生成的Derived类包含$$delegate_0合成字段,IntelliJ项目无此字段
  • 版本信息:Kotlin库版本均为2.0.20,但编译器版本不同——Gradle使用kotlinc 2.0.20,IntelliJ使用kotlinc 1.9.24
  • 复现情况:该问题在Ubuntu与Windows系统的IntelliJ上均可复现

疑问

为何两个项目生成的字节码不同,导致委托行为存在差异?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 18:39:59