For Android developers who are making the transition from Java to Kotlin one of the more interesting features that you will eventually encounter are destructuring declarations.

Destructuring allows you to break an object up into a number of variables. For example you may have a Person class that consists of a name and an age field:

data class Person (val name: String, val age: Int)

Destructuring instances of this class effectively allows you to assign the internals of the Person object to individual fields as shown below:

(1) val person = Person("Thomas", 40)(2) val (name, age) = person // destructuring declaration(3) println("$name is $age years old")

Basically what is happening here is the destructuring declaration on line 2 above is compiled down, behind the scenes, to the following:

val name = person.component1() val age = person.component2()

The Person example shown above is the common example that you will find online, but you may already be thinking to yourself: Self, this is a pretty neat language feature, but how might I use it in the Android world? Good question! To answer it we will take a look at a common characteristic of many Android apps and make an example out of it; the need to deal with location data.

Let’s say that our app has a requirement to process a collection of historical Location data. We’ll keep this example simple and imagine that our product manager has requested that we just write the latitude and longitude of each Location instance within the collection received to the log.

Our first pass might look something like this…

…or perhaps something like this…

With the destructuring and extensions features of the Kotlin language, however, we can make this even more concise by removing the need to explicitly dereference each location object. Let’s take a look.

First we will create extension methods on the existing Android Locationclass so that we can make use of the destructuring language feature:

operator fun Location.component1() = latitude operator fun Location.component2() = longitude

With these in place we can now update our examples above to leverage destructuring. Here is one example…

…or if you prefer, here is another, even more concise example…