Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: How to modify a value in a pair? [duplicate]

Tags:

tuples

kotlin

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

like image 846
Joey Weidman Avatar asked Nov 07 '17 03:11

Joey Weidman


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)
like image 137
ephemient Avatar answered Oct 17 '22 06:10

ephemient