Destructuring Declarations in Kotlin

Destructuring declarations is a Kotlin feature that gives you a tool for easily extracting data from a collection in a simple and clean way. By arjuna sky kok.

Leave a rating/review
Download materials
Save for later
Share

When programming in Kotlin, you work with a lot of data. Sometimes you gather data into a collection, such as an array, pair, data class or class. Of course, you need a way to extract data from these collections, that is Destructuring Declarations and you will learn about it in this tutorial.

There are many ways to extract data from a collection, such as using an index. With destructuring declarations, Kotlin gives you a tool for easily extracting data from a collection, no matter the size of it.

In this tutorial, you’ll build Destructuring Cryptocurrencies, a simple console app that highlights the use of destructuring declarations, while learning the names of different types of cryptocurrencies. You’ll learn about:

  • Destructuring declarations of a pair, array and map.
  • The use case of destructuring declarations in lambda.
  • The gotcha in destructuring declarations of a data class.
  • How to make a class support destructuring declarations.

Getting Started

Download the starter project by clicking Download Materials at the top or bottom of the tutorial. Open the starter project in IntelliJ IDEA.

If you’re not familiar with IntelliJ IDEA, please refer to the sample chapter, Getting started with IntelliJ IDEA, in our Kotlin book. You can also use Kotlin Playground to work on this tutorial.

Open DestructuringCryptocurrencies.kt. In that file, you’ll see some data, including a pair, array and data class. You’ll use destructuring declarations on these later.

Destructuring Declarations

First off, you may be wondering what does the term Destrucutring Declarations means. In simple words it is the process of creating multiple variables in a single line of code. It is a syntax feature of Kotlin that may be hard to understand at first but can come in handy and make your code look cleaner.

It is usually used in collections, or other data types, in this tutorial you will learn how to use them in:

  • Arrays
  • Pairs
  • Maps
  • Lambdas
  • Data classes

You may find other use-cases but this tutorial will give you the tools to apply it anywhere.

Destructuring Declarations of a Pair, Array and Map

The first and most common use of Destructuring Declarations is data structures. Here, you’ll use destructuring declarations with a pair, array and map. These are common data types you might want to extract elements from.

Destructuring Declarations of A Pair

First start with a Pair, which as you may know is a data structure that contains two elements.

To begin Build and run the sample project. Because this is a console app, you can check the app’s output in the run panel window. You’ll find some information:

The initial output of the destructuring declarations starter project

As you can see from the output above, you’ll use destructuring declarations on many kinds of data, such as pairs, arrays and data classes.

First, you’ll use destructuring declarations on a pair. When extracting information from a Pair, you can extract elements one at a time using the first and second properties, which is the most common way. But with destructuring declarations, you can extract both elements from the pair in one go.

Replace TODO 1 with:

val (stringFromPair1, stringFromPair2) = pair
println("$stringFromPair1, $stringFromPair2")

Build and run. You can see the value of stringFromPair1 and stringFromPair2.

The output of destructuring declarations of a pair

Destructuring declarations is similar to declaring a normal variable. You choose whether you want to use val or var. Then you enclose two variables separated by a comma with parentheses.

The code looks much simpler than the extraction sample shown above the code you just added.

You must use val or var for both variables. You can’t use val for one variable and var for other variable. In case you need to use val for one and var for another value, you can’t use destructuring declarations.

If you don’t use destructuring declarations, you’ll need to extract the values one by one using an index operator. Using destructuring declarations saves a couple of extra lines.

However, destructuring declarations don’t just save lines, it’s also more natural in some cases. For example, consider the pair as a data collection of coordinates in a 2D landscape. You can extract x and y one by one from a pair like this:

val x = coordinates[0]
val y = coordinates[1]

But it’s more natural to use destructuring declarations to extract them as a pair, like this:

val (x, y) = coordinates

It’s easier to read because you don’t have to read the index 0 and the index 1, which are superfluous.

Destructuring Declarations of An Array

Next, let’s go on with a more common data structure, that contains not just two values, but many. In the next example, you’ll use destructuring declarations on an array.

First, look at the limitations of destructuring an array and other ways to extract an element from an array. In the code, you will see two examples of how to obtain an element from an array, now imagine having to repeat this for each of the elements. Look at the code below to see which part of the code we are referring to:

The way of destructuring declarations of an array and a pair is the same. However, you can only use destructuring declarations on up to five elements in an array.

Let’s look at an example of this. Uncomment this line:

// val (string1, string2, string3, string4, string5, string6) = stringList

If you uncomment the commented line in the sample code above, you will notice there is an error in the sixth element. Now, the line will look like this:

val (string1, string2, string3, string4, string5, string6) = stringList

Build and run. As you can see, you get an error.

Error on extracting six elements from an array

The error is about missing component6.

Now undo the change. Comment the line again so the line becomes:

// val (string1, string2, string3, string4, string5, string6) = stringList

Build and run again, and the app should be back to normal.

Great job! You have already learned how to do Destructuring Declarations in two data types: Pairs and Arrays. Keep going to learn even more options.

Component1, Component2, …, ComponentN

The error in the previous example lets you know you can use similar methods with indexes below the one it is specifying, such as component5. Doing val componentString5 = stringList.component5() is one way to extract an element from an array. As you may have guessed, you’ll get the fifth element with component5. But as mentioned before you would need to repeat that line several times in order to extract all components.

Nevertheless, Kotlin’s designers thought developers would only need five elements at most when using Destructuring Declarations on an array. This limitation is present in similar data types, like lists.

Later in this tutorial, you’ll see how to add support to a class to extract more than five elements in destructuring declarations.

Another thing to note is that, you’d get a similar error if you uncommented this line val string6 = stringList.component6().

component1, component2 through componentN, where N represents the largest element you want to extract, are the core of destructuring declarations.

Destructuring declarations as syntactic sugar

Destructuring declarations is also one of those Kotlin language features, that are usually known as “syntactic sugar” for accessing component1, component2, …, componentN from an object.

An array or list only supports extracting up to five elements, because their classes only define component1 through component5. You can see the definition of component5 in this Kotlin documentation, but you won’t find the definition of component6.

Besides using a method like component5, you can also extract an element using a conventional method, such as an index, for example stringList[3].

Can you guess why the Kotlin designers set five as the maximum number of elements you can extract in destructuring declarations? If they didn’t put this limit, you could extract ten elements, like this:

val (tree, mountain, bridge, beach, castle, river, waterfall, forest, cave, tower, building, fortress) = words

The line above is more than a hundred characters in width. It’s not good to write code that’s too long because it’s harder to read. You could split the variables with new lines, but at that point, you might as well use the index operator to extract the values.

On top of that, it’s harder to recall several items. In the example above, cave is the ninth item from words. To make sure cave gets the correct value, you have to count from tree as the first element to cave as the ninth element and not make a mistake in the counting process.

You might as well use the index operator like this:

val tree = words[0]
val cave = words[8]

With all this in mind, the Kotlin designers set the maximum number of elements to five when using destructuring declarations with a collection data structure. If you extract more than five elements, you’re abusing the API.

But what if you only want the first element and the fifth element, and not the three elements between them? You’ll learn how to do that next.