Kotlin: How to modify a value in a pair?

Viewed 11603

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 Answers

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)
Related