Why aren't the entries in a Kotlin Pair mutabl

2020-02-12 05:47发布

问题:

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?

回答1:

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)


标签: kotlin