Destructuring

Data classes will generate component functions for all primary constructor properties. For each primary constructor property, a componentX function will be created where X is the order of the property. We can illustrate how this works using the following Article class:

data class Article(var title: String, val author: String) {
var snippet: String = ""
}

For our Article example, the compiler will generate component1() and component2() methods:

public final class Article {
...

@NotNull
public final String component1() {
return this.title;
}

@NotNull

public final String component2() {
return this.author;
}

}

These component functions can then be used by the compiler to support destructuring declarations, shown as follows:

fun main(args: Array<String>) {
val article1 = Article("Kotlin is great", "Nate").apply {
snippet = "an article about Kotlin"
}

val (title, author) = article1
}

In the final expression of the preceding snippet, we are assigning article1.title to the title variable and article1.author to the author variable. Any object can be on the right side of the expression as long as that object has enough component functions to match the number of variables within the parentheses on the left side.

To the compiler, the generated code looks like this:

public static final void main(@NotNull String[] args) {
Intrinsics.checkParameterIsNotNull(args, "args");
Article var2 = new Article("Kotlin is great", "Nate");
var2.setSnippet("an article about Kotlin");
Article var4 = var2;
String var5 = var2.component1();
String author = var4.component2
();
}

In the final lines of this generated code, we see the component functions being called and assigned to new String variables.

If you want to skip over a property, you can use _ to tell the compiler to skip that value. In our example, we could skip the title and use a destructuring declaration to only retrieve the author, using the following code:

fun main(args: Array<String>) {
val article1 = Article("Kotlin is great", "Nate").apply {
snippet = "an article about Kotlin"
}

val (_, author) = article1
}

Data classes are a powerful feature in Kotlin and rely on the compiler generating and enforcing useful functionality to make developers' lives easier. However, data classes are not the only type of special class in Kotlin that aims to enforce best practices.

In the next section, we'll explore several other types of classes available in Kotlin.