Reputation: 536
I have a MutableList of Pairs and I'd like to decrement the value of the first entry so my condition my pass(change):
while(n > 0) {
if(sibice[i].first > 0) {
sum += sibice[i].second
//sibice[i].first-- will not compile
n--
} else i++
}
But the Pair class doesn't let me do that, besides creating my own pair is there any other workaround and why is this even the case?
Upvotes: 15
Views: 11423
Reputation: 39843
Like with all entities, issues arise with mutability.
In your case you can just update the list-entry with a new pair of values.
val newPair = oldPair.copy(first = oldPair.first-1)
Or directly use an array of length 2 instead intArrayOf(0, 0)
. So you can access the elements directly.
while(n > 0) {
if(sibice[i][0] > 0) {
sum += sibice[i][1]
sibice[i][0]--
n--
} else i++
}
You could even define extension values first
and second
to the IntArray
type and use it the same like before.
val IntArray.second get() = get(1)
var IntArray.first
set(value) = set(0, value)
get() = get(0)
Upvotes: 14