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?
Kotlin generates the basic functions that must be overloaded for a good model class, giving us good toString(), hashCode(), and equals() functions. Kotlin also provides some extra functionality in the form of a copy() function, and various componentN() functions, which are important for variable destructuring.
In programming, getters are used for getting value of the property. Similarly, setters are used for setting value of the property. In Kotlin, getters and setters are optional and are auto-generated if you do not create them in your program.
If there are explicit implementations of equals() , hashCode() , or toString() in the data class body or final implementations in a superclass, then these functions are not generated, and the existing implementations are used.
In Kotlin, setter is used to set the value of any variable and getter is used to get the value. Getters and Setters are auto-generated in the code.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With