Hi, is there way to simplify this kotlin statement...
# android
a
Hi, is there way to simplify this kotlin statement, i don't like it taking multiple iterations
Copy code
private 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
you could use
partition
to split the original list into two subsets and then sum each
Copy code
val (first, second) = partition { !it.startsWith(TaxType.WHT.name) }
val vatPlusDiscountTotal = first.sumByDouble { ... }
val whtTotal = second.sumByDouble {... }

return vatPlusDiscountTotal - whtTotal
Something like this
๐Ÿฅฐ 1
๐Ÿ‘ 1
it'll only iterate over the lists once to filter them and split into two subsets and then summing is another iteration over each list but in terms of complexity, both approaches are the same for time, this could/should be a bit better, but it could impact the memory more
at least it's easier to understand I guess ๐Ÿ˜„
๐Ÿ‘ 1
a
thank you @f.babic complexity is the same, however i was more into the readable aspect
z
You could do it very manually with a
for
loop to avoid any extra allocations, but outside of that
partition
is probably the most straightforward and easy to read solution
a
Copy code
private 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
look at @zsmb optimizing the heck out of it! ๐Ÿ˜„
no extra space or time complexity, single loop
z
On second look, I think you could do
Copy code
private 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 otherwise
๐Ÿคฏ 3
๐Ÿ‘ 1
a
@zsmb bravo ๐Ÿ™‚ i never thought this way, out box the box actually ๐Ÿ™‚