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

Kotlin has a data class like

@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 the component1 and component2 functions to access the properties. However, when I declare a var property, I have a getter and setter, and if I declare a val property, I have a getter. In this case, the Component functions are redundant and why do we need them because the getters seem much more understandable?

+5
source share
1 answer

Kotlin supports the following syntax using componentN functions:

 val (name, age) = person 

This syntax is called a destruction declaration . The declaration of destruction creates several variables at once. We announced two new variables: name and age.

The destructuring declaration is compiled to the following code:

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

the functions component1 () and component2 () are another example of the principle of conventions widely used in Kotlin (see operators like + and *, for-loop, etc.). All that may be on the right side of the declaration of destruction, if the required number of components on it can be called functions. And of course, maybe component3 () and component4 (), etc.

Note that the componentN () functions must be marked with the operator keyword icon in order to use them in the destruction declaration.

+14
source

Source: https://habr.com/ru/post/1266210/


All Articles