问题
Why can't I change the values in the pair:
var p: Pair<Int, String> = Pair(5, "Test")
p.first = 3
Error under p.first
: Val cannot be reassigned
回答1:
Pair, like most data classes, is immutable. Its definition is effectively
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.
However, like other data classes, it can be copied with changes.
p = p.copy(first = 3)
来源:https://stackoverflow.com/questions/47149305/kotlin-how-to-modify-a-value-in-a-pair