Search⌘ K
AI Features

Destructuring

Explore how to use destructuring in Kotlin to extract values from objects like Triple and data classes efficiently. Learn to assign multiple variables in a concise way and handle unwanted values with underscores. This lesson helps you write cleaner, more readable Kotlin code.

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 ...