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

Kotlin 2.0.0-Beta3升级后Context Receivers编译错误求助

Kotlin 2.0 Beta3升级后Context Receivers编译报错解决方案

问题背景

在将代码库从Kotlin 2.0.0-Beta2升级到Beta3时,使用Context Receivers结合Arrow库的代码出现编译错误:Not enough information to infer type argument for 'Error'。

示例代码

interface User
object UserNotFound

context(Raise<UserNotFound>)
fun findUser(): User = raise(UserNotFound)

fun main() {
    either {
        findUser()
    }.onLeft {
        println("Uh-oh, $it")
    }
}

原Beta2构建配置

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

plugins {
    kotlin("jvm") version "2.0.0-Beta2"
}

repositories {
    mavenCentral()
}

dependencies {
    implementation(platform("io.arrow-kt:arrow-stack:1.2.4"))
    implementation("io.arrow-kt:arrow-core")
}

tasks.withType<KotlinCompile>().configureEach {
    compilerOptions {
        freeCompilerArgs.add("-Xcontext-receivers")
    }
}

问题原因

这是Kotlin 2.0 Beta3与Arrow 1.2.4的兼容性问题:

  • Kotlin 2.0 Beta3对Context Receivers的类型推断逻辑做了严格化调整;
  • Arrow 1.2.4的either函数实现未适配这一变化,导致编译器无法自动推导Error类型参数。

解决方案

1. 升级Arrow到兼容版本(推荐)

Arrow已发布适配Kotlin 2.0 Beta3+的版本(如1.2.5及以上),修改依赖配置即可解决:

dependencies {
    implementation(platform("io.arrow-kt:arrow-stack:1.2.5"))
    implementation("io.arrow-kt:arrow-core")
}

该版本专门修复了与Kotlin 2.0新类型推断规则的兼容问题。

2. 显式指定类型参数(临时 workaround)

若暂时无法升级Arrow,可在调用either时显式声明泛型参数,帮助编译器完成推断:

fun main() {
    either<UserNotFound, User> {
        findUser()
    }.onLeft {
        println("Uh-oh, $it")
    }
}

3. 保留Context Receivers配置

Kotlin 2.0 Beta3中Context Receivers仍需通过-Xcontext-receivers编译器参数开启,原配置无需修改,确保该参数存在即可。

结论

该问题属于框架与语言版本的适配问题,单纯调整配置无法解决,优先通过升级Arrow版本来彻底修复,临时场景可采用显式指定类型参数的方式绕过报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 02:22:36