So, Why Does This Exist?

If the author had to guess, destructuring declarations were added for use when iterating over a Map:

fun main() {
  val montyPythonCast = mapOf(
    "Graham Chapman" to "Arthur, King of the Britons",
    "John Cleese" to "Sir Lancelot",
    "Terry Gilliam" to "Patsy",
    "Eric Idle" to "Sir Robin",
    "Terry Jones" to "Sir Bedevere",
    "Michael Palin" to "Sir Galahad"
  )

  for ((actor, role) in montyPythonCast) {
    println("$actor -> $role")
  }
}

Normally, a for loop over a Map gives you a single Map.Entry property, and you have to refer to the key and value on that to get to the individual pieces of data that you are looking for. With destructuring declarations, you can have the for loop give you the key and value in individual properties that have useful names (rather than key and value).

This also works with lambda expressions, such as using forEach() on a Map:

fun main() {
  val montyPythonCast = mapOf(
    "Graham Chapman" to "Arthur, King of the Britons",
    "John Cleese" to "Sir Lancelot",
    "Terry Gilliam" to "Patsy",
    "Eric Idle" to "Sir Robin",
    "Terry Jones" to "Sir Bedevere",
    "Michael Palin" to "Sir Galahad"
  )

  montyPythonCast.forEach { (actor, role) -> println("$actor -> $role") }
}

Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.