本文介绍了Kotlin:如何成对修改值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能更改该对中的值:

Why can't I change the values in the pair:

var p: Pair<Int, String> = Pair(5, "Test")
p.first = 3

p.first下的错误:无法重新分配Val

Error under p.first: Val cannot be reassigned

推荐答案

Pair 是不可变的.它的定义是有效的

Pair, like most data classes, is immutable. Its definition is effectively

data class Pair<out A, out B>(val first: A, val second: B)

如果它是可变的,则它在out Aout B中不能协变,也不能安全用作Map键.

If it were mutable, it could not be covariant in out A and out B, nor would it be safe to use as a Map key.

但是,与其他数据类一样,可以复制更改.

However, like other data classes, it can be copied with changes.

p = p.copy(first = 3)

这篇关于Kotlin:如何成对修改值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 08:27