kotlin 使用Arrow 1.2.0 parZipOrAccumulate将错误累积到Nel时无法绑定< ApplicationError>

6l7fqoea  于 2023-04-12  发布在  Kotlin
关注(0)|答案(1)|浏览(136)

我正在使用Arrow 1.2.0-RC中的新parZipOrAccumulate函数来并行化两个调用,并累积它们的错误(如果有的话):

private suspend fun getUser(legalId: UserLegalId): Either<ApplicationError, User>
private suspend fun getDepartment(departmentCode: DepartmentCode): Either<ApplicationError, Department>
override suspend fun execute(param: AddUserToDepartmentInfo): Either<Nel<ApplicationError>, Department> = either {
            val pair: Pair<User, Department> =
                parZipOrAccumulate<ApplicationError, User, Department, Pair<User, Department>>(
                    {e1: ApplicationError, e2 : ApplicationError-> nonEmptyListOf(e1,e2)},
                    { getUser(param.userLegalId).bind() },
                    { getDepartment(param.departmentCode).bind() }
                ) { a, b -> Pair(a, b) }
            saveUserDrivenPort.save(pair.first.copy(departmentId = param.departmentCode)).bind()
            pair.second
        }

上面代码中的三个.bind()调用都不能编译,因为它期望错误类型匹配(x1m2 n1<->xx 1 m3n1x)。
当我需要用ApplicationError绑定可能失败的函数时,如何在Nel<ApplicationError>中积累错误?

t5fffqht

t5fffqht1#

作为answered in this related question,我们可以摆脱组合子函数,错误将自动添加到Nel。

override suspend fun execute(param: AddUserToDepartmentInfo): Either<Nel<ApplicationError>, Department> = either {
            val pair: Pair<User, Department> =
                parZipOrAccumulate(                   
                    { getUser(param.userLegalId).bind() },
                    { getDepartment(param.departmentCode).bind() }
                ) { a, b -> Pair(a, b) }
            saveUserDrivenPort.save(pair.first.copy(departmentId = param.departmentCode)).mapLeft { nonEmptyListOf(it) }.bind()
            pair.second
        }

相关问题