当结果应该有值或没有值时改进 applicativeNel 验证

问题描述

我目前正在学习使用 ArrowKT,我有以下用于验证输入的代码。我尝试一次收集所有错误并并行执行验证,因为其中大部分都是针对数据库完成的。

return Validated.applicativeNel<ValidationError>()
    .tupledn(
        validateA(input).tovalidatednel(),validateB(input).tovalidatednel(),validateC(input).tovalidatednel(),validateSlotIsFree(input).tovalidatednel(),)
    .fix()
    .map { (a,b,c,_) ->
        ...
    }

private suspend fun validateSlotIsFree(input: CreateDto): Validated<ValidationError.SlotUnavailable,Boolean> {
    val exists = appointmentRepository.existsBy...()
    return if (exists) true.valid() else ValidationError.SlotUnavailable.invalid()
}

有没有更好的方法来处理 validateSlotIsFree 中的验证?看起来我被迫在右侧返回一些有效的东西,但我不想。我正在寻找类似 Option 的东西,其中值将是 Error 并且空意味着验证已通过。这样做的问题是 Validated.fromOption(...) 会取值并将其应用于右侧,而我需要相反的内容

解决方法

使用@LordRaydenMK 和@MLProgrammer-CiM 的答案,我找到了两个解决方案

span.root

以前我尝试过使用 private suspend fun validateSlotIsFree(input: CreateAppointmentDto): Validated<ValidationError.SlotUnavailable,Unit> { val exists = appointmentRepository.existsBy...() return if (exists) Valid(Unit) else ValidationError.SlotUnavailable.invalid() } 但它不起作用。原因是 Nothing 没有可能的值,这就是使用 Nothing 不起作用的原因。为了让它与 null 一起使用,我必须使用 null

首选第一种解决方案,因为使用 Nothing? 是不正确的,因为它实际上表示此函数不返回任何内容,同时它可以返回 Nothing?