如何在 Kotlin 中将 Pair 对象解构为两个变量

Ser*_*gey 11 tuples kotlin

我有一个返回的函数Pair

fun createTuple(a: Int, b: Int): Pair<Int, Int> {
    return Pair(a, b)
}
Run Code Online (Sandbox Code Playgroud)

我想初始化变量ab使用此函数,然后在循环内重新分配它们:

var (a, b) = createTuple(0, 0)
for (i in 1..10) {
    createTuple(i, -i).let{
       a = it.first
       b = it.second
    }
    println("a=$a; b=$b")
}
Run Code Online (Sandbox Code Playgroud)

使用起来let感觉很别扭。有没有更好的方法来解开Pair内部循环?

以下行不会编译:

(a, b) = createTuple(i, -i)
a, b = createTuple(i, -i)
Run Code Online (Sandbox Code Playgroud)

小智 7

var (a, b) = createPair(0, 0)对我来说编译得很好。

您的问题可能是使用createTuple(i, -i)而不是createPair(i, -i).