Home > Software engineering >  Difference between accessing via property access and destructuring in kotlin data class
Difference between accessing via property access and destructuring in kotlin data class

Time:11-23

I have a data class like this

data class Task(
    var id: Int,
    var description: String,
    var priority: Int
)

I implement it the following

val foo = Task(1, "whatever", 10)

I read about accessing whatever like this

foo.description

or

foo.component2()

What is the difference?

CodePudding user response:

There is no difference in behaviour, but use foo.description.

It's extremely rare to use a componentN() function directly. If you know which component you're accessing, it's just way more readable to use the property directly.

The componentN() functions are mostly a tool to implement actual destructuring declarations like:

val (id, desc, prio) = task

Which is a shortcut that is equivalent to:

val id = task.component1()
val desc = task.component2()
val prio = task.component3()

..which you should probably never write in source code.

  • Related