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

求助:Kotlin Arrow中mapOrAccumulate()用法理解误区

问题分析与解决

问题根源

你手动指定的泛型参数<Throwable, Int, Any>干扰了mapOrAccumulate的逻辑。该函数的设计是解析转换函数返回的Either<E, B>,将Left中的错误累加、Right中的结果收集。但你指定B为Any后,函数会把checkEven(it)返回的Either<Throwable, String>整体当成Any类型的成功值,而不会拆解其中的Left和Right,最终所有Either实例都被直接放入Right的列表中。

修正方案

去掉手动指定的泛型参数,让编译器自动推断正确的类型:

fun checkAllEven(inputs: List<Int>): Either<NonEmptyList<Throwable>, List<String>> {
    return inputs.mapOrAccumulate {
        println(it)
        checkEven(it)
    }
}

或者明确指定正确的泛型参数(B为String,即checkEven返回的Right类型):

fun checkAllEven(inputs: List<Int>): Either<NonEmptyList<Throwable>, List<String>> {
    return inputs.mapOrAccumulate<Throwable, Int, String> {
        println(it)
        checkEven(it)
    }
}

修正后的行为

对于输入listOf(0,1,2,3,4,5),函数会返回Left(NonEmptyList(Throwable("1 not even!"), Throwable("3 not even!"), Throwable("5 not even!"))),符合你“收集所有失败结果到Left,成功结果到Right”的预期。如果输入全为偶数,则返回Right(List("0 even", "2 even", ...))。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 08:30:59