WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Kotlin · Intermediate · question 28 of 100

What is the role of destructuring declarations in Kotlin? Provide an example.?

📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

In Kotlin, destructuring declarations are used to unpack values from objects and arrays into separate variables. This can make the code more concise and readable, especially when dealing with complex data structures.

The syntax for destructuring declarations is as follows:

val (var1, var2, ...) = expression

Here, ‘expression‘ can be any object or array that implements the ‘component1()‘, ‘component2()‘, etc. functions, which are used to extract the individual values. The variables ‘var1‘, ‘var2‘, etc. are then assigned the corresponding values from ‘expression‘.

For example, consider the following data class representing a person’s name:

data class Name(val firstName: String, val lastName: String)

We can create an instance of this class and destructure its properties as follows:

val (first, last) = Name("John", "Doe")
println("First name: $first, Last name: $last")

This will print out:

First name: John, Last name: Doe

We can also use destructuring declarations to unpack values from arrays or lists:

val numbers = listOf(1, 2, 3, 4, 5)
val (first, second, *rest) = numbers
println("First value: $first, Second value: $second, Rest: $rest")

This will print out:

First value: 1, Second value: 2, Rest: [3, 4, 5]

In this example, the ‘*rest‘ syntax is used to unpack the remaining values in the list into a new list called ‘rest‘.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Kotlin interview — then scores it.
📞 Practice Kotlin — free 15 min
📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

All 100 Kotlin questions · All topics