kotlin 如何使用context receiver和Arrow 1.2.0 parZipOrAccumulate?没有找到所需的context receiver:Cxt

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

给定以下功能:

context(Raise<ApplicationError>)
suspend fun getUser(legalId: UserLegalId): User
context(Raise<ApplicationError>)
suspend fun getDepartment(departmentCode: DepartmentCode): Department
context(Raise<ApplicationError>)
suspend fun save(user: User): User

我想并行调用它们并累积它们的错误:

context(Raise<Nel<ApplicationError>>)
        override suspend fun execute(param: AddUserToDepartmentInfo): Department {
            val pair: Pair<User, Department> =
                parZipOrAccumulate(
                    {e1, e2 -> e1 + e2},
                    { getUser(param.userLegalId) },
                    { getDepartment(param.departmentCode) }
                ) { a, b -> Pair(a, b) }
            saveUserDrivenPort.save(pair.first.copy(departmentId = param.departmentCode))
            return pair.second
        }

但是,parZipOrAccumulate中的getUser()getDepartment()调用无法编译:

No required context receiver found: Cxt { context(arrow.core.raise.Raise<xxx.ApplicationError>) private open suspend fun getUser(...)
drkbr07n

drkbr07n1#

你能试着省略{e1, e2 -> e1 + e2}参数吗?在这种情况下不需要,因为Nel累加器是由外部Nel<ApplicationError>推断的。

context(Raise<Nel<ApplicationError>>)
suspend fun execute(param: AddUserToDepartmentInfo): Department {
  val pair: Pair<User, Department> =
    parZipOrAccumulate(
      { getUser(param.userLegalId) },
      { getDepartment(param.departmentCode) }
    ) { a, b -> Pair(a, b) }
  return TODO()
}

我在本地试过了,它对我很有效。Raise<ApplicationError>parZipOrAccumulate的lambda中被暴露为ScopedRaiseAccumulate<ApplicationError>

相关问题