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

