为什么Kotlin Pair中的条目不可变? [英] Why aren't the entries in a Kotlin Pair mutable?

查看:643
本文介绍了为什么Kotlin Pair中的条目不可变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个成对的MutableList,我想减小第一个条目的值,所以我的条件是pass(change):

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++
}

但是Pair类不允许我这样做,除了创建自己的对之外,还有其他解决方法,为什么会这样呢?

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?

推荐答案

就像所有实体一样,可变性也会引起问题.

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)

或直接使用长度为2的数组代替intArrayOf(0, 0).因此,您可以直接访问元素.

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++
}

您甚至可以将扩展值firstsecond定义为IntArray类型,并像以前一样使用它.

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 Pair中的条目不可变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆