11
votes

There is a data class in kotlin, e.g.

@Entity
data class Record(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long? = null,
    @Column(nullable = false, name = "name")
    var name: String? = null
)

And I can call component1 and component2 functions to access the properties. However, as I declare the property var, I have getter and setter, and if I declare property val I have the getter. Are componentN functions are redundant in this case, and why do we need them, because getters seem to be much more self-explanatory?

1

1 Answers

23
votes

Kotlin supports the following syntax via componentN functions:

val (name, age) = person 

This syntax is called a destructuring declaration. A destructuring declaration creates multiple variables at once. We have declared two new variables: name and age.

A destructuring declaration is compiled down to the following code:

val name = person.component1()
val age = person.component2()

the component1() and component2() functions are another example of the principle of conventions widely used in Kotlin (see operators like + and *, for-loops etc.). Anything can be on the right-hand side of a destructuring declaration, as long as the required number of component functions can be called on it. And, of course, there can be component3() and component4() and so on.

Note that the componentN() functions need to be marked with the operator keyword to allow using them in a destructuring declaration.