首页 > 解决方案 > Kotlin 中的多重赋值

问题描述

我可以声明和初始化ab就像这样

var (a, b) = Pair(1, 2)

但我不能像这样重新分配它们

(a, b) = Pair(3, 4)

这怎么不可能?我错过了什么吗?

标签: kotlin

解决方案


那是因为(a, b)是 2 个单独的变量,您可以通过componnetN()函数进行初始化。
您可以使用 a 和 b 作为不同的变量。如果你有对,你必须这样写var a = Pair(2, 1)或者可以使用 vara = 1 to 2

在这里阅读更多信息
https://kotlinlang.org/docs/destructuring-declarations.html


推荐阅读