Search code examples
androidkotlindestructuring

Destructuring declaration in Kotlin results in type errors


In the code below, when I call holder.imgAvatar.setImageResource(avatar), it says that my variable (avatar) is String, even though I already set it to Int in the data class.

Why is this happening?

ListUserAdapter.kt

class ListUserAdapter(val listUser: ArrayList<User>) {
    // ...
    fun someMethod() {
        val (name, username, avatar) = listUser[position]
        holder.imgAvatar.setImageResource(avatar)
        holder.tvName.text = name
        holder.tvUserName.text = username

User.kt

@Parcelize
data class User(
    var username: String,
    var name: String,
    var location: String,
    var company: String,
    var repository: String,
    var followers: String,
    var following: String,
    var avatar:Int,
):Parcelable

Solution

  • Destructuring declarations are not based on the variable names but rather on consequential calls to the componentN() method of the data class.

    What I mean by that is that Your code:

    val (name, username, avatar) = listUser[position]
    

    Does not mean:

    val name = listUser[position].name
    val username = listUser[position].username
    val avatar = listUser[position].avatar
    

    But it means:

    val name = listUser[position].component1()
    val username = listUser[position].component2()
    val avatar = listUser[position].component3()
    

    Which can be understood as:

    val name = listUser[position].username
    val username = listUser[position].name
    val avatar = listUser[position].location
    

    So the avatar value gets the value of the location from the listUser[position].

    You should rather get the reference to the User that You need from the list and basically assign the values yourself. Or You can change the order of the values of the User data class.

    You can read on the destructuring declarations more here.