为什么我不能更改配对中的值:
var p: Pair<Int, String> = Pair(5, "Test")
p.first = 3
Error under p.first
: Val cannot be reassigned
为什么我不能更改配对中的值:
var p: Pair<Int, String> = Pair(5, "Test")
p.first = 3
Error under p.first
: Val cannot be reassigned
像大多数数据类一样,Pair是不变的.它的定义是有效的
data class Pair<out A, out B>(val first: A, val second: B)
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.
然而,和其他数据类一样,它可以是copied with changes.
p = p.copy(first = 3)