I faced the following problem: I have a list of objects. Let it be objects of the class Test:
data class Test(
var status: String, // Can be EXPIRED, WAIT
var amount: Float
)
The array is sorted, there are objects with the status EXPIRED
in the beginning and after objects with the status WAIT
located. I need to calculate the sum of all elements with the status EXPIRED
(if they exist) and add to this sum amount of the first object with the type WAIT
(if it exists). Now I have the following code:
private fun getRestructuringAmountToPay(): Float {
var i = 0
var sum = 0F
list?.forEachIndexed { iter, el ->
if (el.status != RestructingItemStatus.WAIT) {
i = iter
sum += el.amount ?: 0F
}
}
if (i + 1 < (list?.size ?: 0)) {
sum += list?.get(i+1)?.amount ?: 0F
}
return sum
}
But is there any way to improve this code and make it Kotlin-pretty? Thanks in advance for any help!
question from:
https://stackoverflow.com/questions/65906804/count-sum-of-all-list-elements-until-condition-is-satisfied 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…