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
相关产品推荐
相关产品推荐

