Is there a clean way to bind multiple variables to...
# getting-started
j
Is there a clean way to bind multiple variables to a local scope? Similar to
.let
, but for an arbitrary number of variables and types.
Copy code
"X".let { x ->
  "Y".let { y ->
    "Z".let { z ->
      println(x + y + z) // XYZ
    }
  }
}
In Clojure, the
let
-form lets us do it like this
Copy code
(let [x "X"
      y "Y"
      z "Z"]
  (println (str x y z))) ;; "XYZ"
How would you do this in Kotlin? Could perhaps invoke
.let
on a hashmap with values of type
Any
, but at that point i’d probably just extract it to a function instead
k
you can use destructuring depending on where x,y,z come from. e.g. val (x,y,z) = someArray
j
Copy code
run {
 val x = "x"
 val y = "Y"
 val z = "Z"
println(x + y + z) // XYZ
}
☝️ 3
j
Perfect, thanks both!
j
Alternatively to destructuring an array, you can also destructure a Triple. (The same is true for the Pair class)
Copy code
val (x, y, z) = Triple("X", "Y", "Z")

println(x + y + z) // "XYZ"
println("$x$y$z") // "XYZ", but using string interpolation
n
you can also combine the two:
Copy code
run {
    val (x, y, z) = listOf("X", "Y", "Z")
    println(x + y + z) // XYZ
}