Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does kotlin have componentN functions in data class, if they already have getters and setters?

Tags:

kotlin

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?

like image 996
lopushen Avatar asked Apr 01 '17 15:04

lopushen


People also ask

Can data classes have functions Kotlin?

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.

Are getters and setters necessary in Kotlin?

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.

What happens if you explicitly provide equals function to a data class in Kotlin?

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.

Does Kotlin generate getters and setters?

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.


1 Answers

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.

like image 71
Yoav Sternberg Avatar answered Sep 28 '22 07:09

Yoav Sternberg