Sergey
Sergey

Reputation: 1348

How to destructure a Pair object into two variables in Kotlin

I have a function that returns Pair:

fun createTuple(a: Int, b: Int): Pair<Int, Int> {
    return Pair(a, b)
}

I want to initialize variables a and b using this function and then reassign them inside loop:

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")
}

Using let seems awkward. Is there a better way to unwrap Pair inside loop?

The following lines do not compile:

(a, b) = createTuple(i, -i)
a, b = createTuple(i, -i)

Upvotes: 15

Views: 14378

Answers (1)

ByteZ
ByteZ

Reputation: 159

var (a, b) = createPair(0, 0) compiles fine for me.

Your problem probably is using createTuple(i, -i) instead of createPair(i, -i).

Upvotes: 7

Related Questions