我有一個問題,如何在 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?> */
還有其他優雅的方法來處理這個嗎?
uj5u.com熱心網友回復:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/496899.html
上一篇:如何使用CSS制作回應式網格
