Reputation: 2104
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
Upvotes: 4
Views: 1488
Reputation: 23129
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.
Upvotes: 10