Search code examples
androidkotlinsparse-matrix

Best way to sum all values of a SparseIntArray


What is the best way to sum all the values of a SparseIntArray in Kotlin ?

I try something but it's not working... This is my code (quantities is the SparseIntArray) :

var amount = 0
for (q in quantities){
     amount += q
}

But I have this error :

For loop range must have an 'iterator()' method

Be careful : my problem don't concern ArrayList but SparseIntArray.


Solution

  • You need to do this manually:

    var amount = 0
    for (i in 0 until quantities.size()) {
        amount += quantities.valueAt(i)
    }
    

    If you use android-ktx, you can also rewrite this as:

    var amount = 0
    quantities.forEach { k, v -> amount += v }