We'll cover the following

What is destructuring

Structuring, or construction, is creating an object from values in different variables. Destructuring is the opposite—to extract values into variables from within an existing object. This facility is useful to remove noisy, repetitive code. Kotlin has the destructuring capability much like in languages such as JavaScript. But unlike JavaScript, the destructuring in Kotlin is based on the position of properties instead of the names of the properties.

Let’s start with a piece of code that is verbose and then refactor that code, using destructuring, to make it concise. Triple is a class in the Kotlin standard library that represents a tuple. We’ll look at it further in Using Pair and Triple. For now, we’ll use Triple to return a group of three values:

// destructuring.kts
fun getFullName() = Triple("John", "Quincy", "Adams")

Here’s a traditional, boring, call to the above function, to receive the result and assign to three different variables.

Get hands-on with 1200+ tech skills courses.