four-eyes
four-eyes

Reputation: 12439

Difference between accessing via property access and destructuring in kotlin data class

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?

Upvotes: 1

Views: 45

Answers (1)

Joffrey
Joffrey

Reputation: 37729

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.

Upvotes: 1

Related Questions