skip to Main Content

Beyond Positions: Kotlin’s New Name-Based Destructuring

March 18, 20262 minute read

  

Image generated using Perplexity

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

https://kotlinlang.org/docs/whatsnew2320.html#language

Mode — Name-Mismatch

⚠️ Warning ⚠️

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.

 

Web Developer, Web Design, Web Builder, Project Manager, Business Analyst, .Net Developer

No Comments

This Post Has 0 Comments

Leave a Reply

Back To Top