althaf
03/30/2022, 7:40 AMprivate fun List<PaymentTaxDiscountDetail.PaymentTaxDiscount>.getTotalTaxDiscount(): Double {
var vatPlusDiscountTotal = sumByDouble {
if (!it.taxType.startsWith(TaxType.WHT.name)) it.whtAmount else 0.0
}
val whtTotal = sumByDouble {
if (it.taxType.startsWith(TaxType.WHT.name)) it.whtAmount else 0.0
}
return vatPlusDiscountTotal - whtTotal
}
f.babic
03/30/2022, 7:42 AMpartition
to split the original list into two subsets and then sum eachf.babic
03/30/2022, 7:44 AMval (first, second) = partition { !it.startsWith(TaxType.WHT.name) }
val vatPlusDiscountTotal = first.sumByDouble { ... }
val whtTotal = second.sumByDouble {... }
return vatPlusDiscountTotal - whtTotal
Something like thisf.babic
03/30/2022, 7:45 AMf.babic
03/30/2022, 7:46 AMalthaf
03/30/2022, 7:46 AMzsmb
03/30/2022, 7:48 AMfor
loop to avoid any extra allocations, but outside of that partition
is probably the most straightforward and easy to read solutionalthaf
03/30/2022, 7:49 AMprivate fun List<PaymentTaxDiscountDetail.PaymentTaxDiscount>.getTotalTaxDiscount(): Double {
val (whtAmounts, vatAndDiscounts) = partition { it.taxType.startsWith(TaxType.WHT.name) }
return vatAndDiscounts.sumByDouble { it.whtAmount } - whtAmounts.sumByDouble { it.whtAmount }
}
f.babic
03/30/2022, 7:51 AMf.babic
03/30/2022, 7:51 AMzsmb
03/30/2022, 8:00 AMprivate fun List<PaymentTaxDiscountDetail.PaymentTaxDiscount>.getTotalTaxDiscount2(): Double {
return sumOf {
if (!it.taxType.startsWith(TaxType.WHT.name)) it.whtAmount else -it.whtAmount
}
}
This adds to the sum if the tax type is not WHT and subtracts from it otherwisealthaf
03/30/2022, 8:19 AM