Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destructure a Pair object into two variables in Kotlin

Tags:

tuples

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)
like image 504
Sergey Avatar asked Dec 18 '25 19:12

Sergey


1 Answers

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

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

like image 148
ByteZ Avatar answered Dec 21 '25 21:12

ByteZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!