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

无人久伴 提交于 2019-12-23 14:40:30

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!