How to destructure a Pair object into two variables in Kotlin
Asked Answered
P

1

12

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)
Pillbox answered 2/9, 2020 at 20:10 Comment(4)
Destructuring assignment is not supported. There's an open issue for it on the tracker that's a few years old. If you use run instead of let, you can drop the its.Liselisetta
Your question is very unclear on what you want to achieve. Here, you could just do for (i in 1..10) { a = i; b = -i }Carleecarleen
@SiddharthSharma it is a minimal example. My question was about destructuring assignment and Tenfour04 answered itPillbox
@Pillbox Haha okay, then your question could have been a lot more minimal. For example, "How to destructure a Pair object into two existing variables"Carleecarleen
M
7

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

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

Maxine answered 2/9, 2020 at 20:26 Comment(2)
Sorry, it was a copy/paste error. My answer was about destructuring assignment, see Tenfour04 commentPillbox
Too bad this is only supported for local variables: "Destructuring declarations are only allowed for local variables/values" I'd like to declare two class members in one step: val (a,b) = createPair(0,0)Miller

© 2022 - 2024 — McMap. All rights reserved.