我有一个问题,我如何在kotlin中验证超过10个值。
fun CreateEventDTO.validate(): Validated<IncorrectInput, CreateEventDTO> =
name.isEventNameValid()
.zip(
about.isAboutValid(),
phone.isPhoneValid(),
price.isPriceValid(),
location.isLocationValid(),
startDate.isStartDateValid(),
// TODO add common validation for date
// endDate.isEndDateValid(),
status.isEventStatusValid(),
access.isEventAccessValid(),
category.isEventCategoryValid(),
musicStyles.isMusicStyleValid()
)
{ name, _, _, price, location, status, access, category, musicStyles ->
CreateEventDTO(
name = name,
about = about,
phone = phone,
price = price,
location = location,
startDate = startDate,
endDate = endDate,
status = status,
access = access,
category = category,
musicStyles = musicStyles
)
}
.mapLeft(ApiError::IncorrectInput)
如果我尝试再添加一个验证就会得到一个错误因为zip只允许最多10个值
Required:
Semigroup<TypeVariable(E)>
Found:
ValidatedNel<InvalidAbout, String?> /* = Validated<NonEmptyList<InvalidAbout>, String?> */
是否有其他优雅的方法来处理这个问题?
Kotlin要求显式定义所有函数,并且我们不能定义无限数量的方法。因此,Arrow决定将参数限制为9个。
但是,您可以使用元组轻松地组合不同的zip
方法。对于达到10个参数,您可以按照以下方式组合9 + 2
。
fun CreateEventDTO.validate(): Validated<IncorrectInput, CreateEventDTO> =
name.isEventNameValid()
.zip(
about.isAboutValid(),
phone.isPhoneValid(),
price.isPriceValid(),
location.isLocationValid(),
startDate.isStartDateValid(),
endDate.isEndDateValid(),
status.isEventStatusValid(),
access.isEventAccessValid(),
category.isEventCategoryValid().zip(musicStyles.isMusicStyleValid(), ::Pair)
)
{ name, _, _, price, location, startDate, endDate, status, access, (category, musicStyles) ->
CreateEventDTO(
name = name,
about = about,
phone = phone,
price = price,
location = location,
startDate = startDate,
endDate = endDate,
status = status,
access = access,
category = category,
musicStyles = musicStyles
)
}
.mapLeft(ApiError::IncorrectInput)