Androibites | Destructuring Params with safety โ

If you havenโt gone through my previous article this post won't make a lot of sense why we should be only destructuring only in the mentioned places. I will highly recommend going through it.

If you're done! then welcome back. So from the above article, you would be clear what are the limitations and risks involved with destructuring. So you might be thing why to even use it, I will say it's not necessary to use it, but there are some areas where they just make sense and are risk-free, so go through these list till the end and I will share a sneaky trick to overcome the problem related of positional destructuring with data classes which could survive even refactoring changes.
Destructuring Collections ๐งฎ
//map
val map: HashMap<Int, String> = HashMap()
map.put(1, "person")
map.forEach { entry->
val(key,value) = entry
...
}
//List or Arrays
val threeItemList = listOf("one", "two", "three")
val (itemOne, itemtwo) = threeItemList
...
Destructuring in Lambda Receivers ๐๐ปโโ๏ธ
map.forEach{key,value ->
...
// this api is Available in android from API 24+
}
//You can achieve the same result using destructuring
map.forEach { (key,value)->
...
}
Destructuring in for loop ๐
for ((key, value) in map) { ... }
or
for ((item,index) in list.withIndex()){...}
Destructuring Pairs ๐จโ๐ง or triplets ๐จโ๐งโ๐ฆ
// trick to swap two numbers using pairs
val (a,b) = Pair<Int,Int>(y,x)
and
val (a,b,c) = Triplet<Int,Int,Int>(x,y,z)
Destructuring Data classes ๐ป
So the main problem destructuring data classes is because of the position of the members, if it would have been structural or named it wouldnโt have been the issue. (Again if you don't know what I'm talking about read my previous article). So I will highly recommend not to destructuring on data class, but ... there is a way around it if you want to,
The whole Idea behind Kotlin's destructuring supports is that it's only positional, So we just need to enforce position to the members of the data class.
To know how we can do that ๐ on the code ๐.
data class Contact(val email:String ,val twitter:String)
data class Person(val contact:Contact,val name:String, val phone:Long)
val contact = Contact("dev.ch8n@gmail.com","twitter@Ch8n2")
val dev = Person(contact,"ch8n",99999999)
// using list to enforce the position to the members of dataclass
val (email, twitter, name, phone) = listOf(
dev.contact.email,
dev.contact.twitter,
dev.name,
dev.phone)
Let me know If I missed something or you have any more tricks like these up your sleeves ๐ง๐ปโโ๏ธ. reach me out on dev.ch8n@gmail.com
or my twitter ch8n2
That's all fokes ๐ฐ๐ฅ ! See ya again in next post .. Happy Hacking ๐ป .
Enjoy the article?
a clap is much appreciated if you enjoyed. No sign up or cost associated :)