Careeroza
Destructuring Declarations
componentN Functions
A data class gets component1(), component2()... in the order of the constructor properties. They let you unpack an object into variables in one line.
Example
data class Employee(val name: String, val dept: String, val salary: Int)
fun main() {
val e = Employee("Divya", "Android", 90000)
val (name, dept, salary) = e
println("$name works in $dept and earns $salary")
println(e.component2())
val (onlyName, _, pay) = e // _ skips a value
println("$onlyName -> $pay")
}Output
Divya works in Android and earns 90000 Android Divya -> 90000
Destructuring in Loops, Maps and Lambdas
Example
data class Score(val player: String, val runs: Int)
fun topScorer(scores: List<Score>): Pair<String, Int> {
val best = scores.maxBy { it.runs }
return best.player to best.runs // Pair
}
fun main() {
val scores = listOf(Score("Virat", 82), Score("Rohit", 45), Score("Gill", 104))
for ((player, runs) in scores) println("$player: $runs")
val (who, howMany) = topScorer(scores)
println("Top scorer: $who ($howMany)")
val capitals = mapOf("Telangana" to "Hyderabad", "Karnataka" to "Bengaluru")
for ((state, city) in capitals) println("$state -> $city")
capitals.forEach { (state, city) -> println("${state.take(3)}: $city") }
}Output
Virat: 82 Rohit: 45 Gill: 104 Top scorer: Gill (104) Telangana -> Hyderabad Karnataka -> Bengaluru Tel: Hyderabad Kar: Bengaluru
Note: Pair and Triple are ready-made data classes. Use them for quick returns, but create a named data class when the meaning matters (Score is clearer than Pair<String, Int>).
Exercise
Exercise: Write a function minMax(list: List<Int>) that returns a Pair of the smallest and largest numbers, then destructure the result.
Show answer
fun minMax(list: List<Int>) = list.min() to list.max()
fun main() {
val (lo, hi) = minMax(listOf(7, 2, 9, 4))
println("min=$lo max=$hi") // min=2 max=9
}