将确定列表扩展为 Kotlin 中的变量

Expand a definite list into variables in Kotlin

检查下面的代码[这工作正常]

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

在Kotlin中,有没有更好的方法将定数组的值取到这些变量中,比如

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

您真的尝试 运行 您的代码吗?它工作得很好:

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

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

输出:

1
2
3

它起作用的原因是因为 Kotlin 的 destructuring declarations. For lists, you can do this for up to 5 items because it has 5 component functions 定义。