
Name-based destructuring declarations were introduced in Kotlin 2.3.20 and match variables to properties rather than relying on position-based componentN().
Previously, destructive declarations used position-based destruction:
data class User(var firstName: String, var lastName: String)
val user = User("Alice", "Husseini")
// componentN()
val(firstName,lastName) = user
println(firstName)
println(lastName)
Drawback of the componentN() based approach
- Destructuring relies on the order of componentN() functions, lastName receives the value of firstName, and firstName receives the value of lastName 👇
data class User(var firstName: String, var lastName: String)
val user = User("Alice", "Husseini")
// componentN()
val(lastName,firstName) = user
println(firstName) -> Husseini
println(lastName) -> Alice
Name-based destructuring ✨
- It’s an Experimental feature.
- We can control how the compiler interprets destructuring declarations with the -Xname-based-destructuring compiler option.
kotlin {
// ..
compilerOptions {
freeCompilerArgs.add("-Xname-based-destructuring=only-syntax")
}
}
Each variable refers to a property by name.
val user = User("Alice", "Husseini")
// Name-based destructuring
(val firstName = firstName, val lastName = lastName) = user
Modes

Mode — Name-Mismatch
⚠️ Warning ⚠️

Mode — Complete
- Position-based destructuring using square brackets []:
data class User(var firstName: String, var lastName: String)
val user = User("Alice", "Husseini")
// componentN()
val [firstName,lastName] = user
References
What’s new in Kotlin 2.3.20 | Kotlin
Stay in touch
https://www.linkedin.com/in/navczydev/
Beyond Positions: Kotlin’s New Name-Based Destructuring was originally published in ProAndroidDev on Medium, where people are continuing the conversation by highlighting and responding to this story.




This Post Has 0 Comments