Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand a definite list into variables in Kotlin

Check this below code [this works fine]

val a = "1,2,3"

val split = a.split(",")
val x = split.get(0)
val y = split.get(1)
val z = split.get(2)

println(x) // 1
println(y) // 2
println(z) // 3

In Kotlin, is there a better way to get the value of a definite array into these variables, like

val a = "1,2,3"
val (i, j, k) = a.split(",") // ...{some magic code to put each item against variables i,j,k}

// This is how i want to use it
println(i) // 1
println(j) // 2
println(k) // 3
like image 570
zero Avatar asked Oct 16 '25 18:10

zero


1 Answers

Did you actually try to run your code? It works just fine:

val a = "1,2,3"
val (i, j, k) = a.split(",")

println(i)
println(j)
println(k)

Output:

1
2
3

The reason it works is because of Kotlin's destructuring declarations. For lists, you can do this for up to 5 items because it has 5 component functions defined.

like image 115
Adam Millerchip Avatar answered Oct 18 '25 17:10

Adam Millerchip