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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With