如何以函数式编程方式实现此功能?

时间:2017-11-24 16:06:19

标签: functional-programming kotlin

如何将此功能转换为纯函数(函数式编程)?

    fun validateOffer(offerValidateRequest: OfferValidateRequest, channelId: ChannelId, tenant: Tenant): OfferValidateRepresentation {

    val errorsList = mutableListOf<OfferValidateErrorsRepresentation>()
    val successList = mutableListOf<OfferValidateSuccessRepresentation>()

    offerValidateRequest.offers.forEach {
        val filterRequest = OfferGetRequest(it.id, it.type)
        val catalogs = findCatalogsWithOffers(filterRequest, channelId, tenant)
        val errorMessages = getOfferErrorMessages(it, catalogs, filterRequest)

        if (errorMessages.isEmpty()) {
            successList.add(OfferValidateSuccessRepresentation(it.id, it.type))
        } else {
            errorsList.add(OfferValidateErrorsRepresentation(it.id, it.type, errorMessages))
        }
    }
    return OfferValidateRepresentation(errorsList, successList)
}

我对错误和成功列表中的这些迭代不太满意。

1 个答案:

答案 0 :(得分:1)

实际上你的功能已经很纯粹了。它没有副作用。

但是你仍然可以通过使用map,partitionpair解构声明来避免可变列表。

如果我通过功能操作替换for循环,我尝试使用多个map,filter,flatMaps。关于这一点的好处是,在这些操作之间唯一的共享数据是您传递的集合。

val (successList, errorsList) = offerValidateRequest.offers.map {
    val filterRequest = OfferGetRequest(it.id, it.type)
    val catalogs = findCatalogsWithOffers(filterRequest, channelId, tenant)
    val errorMessages = getOfferErrorMessages(it, catalogs, filterRequest)
    Pair(it, errorMessages)
}.partition {
    it.second.isEmpty()
}

return OfferValidateRepresentation(
    errorsList.map { OfferValidateErrorsRepresentation(it.first.id, it.first.type, it.second.errorMessages) }, 
    successList.map { OfferValidateSuccessRepresentation(it.first.id, it.first.type) }
 )