Learn about the Kotlin data class

Tram Ho

As the meaning of the name is given, the data class is the class that holds the data. The difference from a normal class is that this class automatically creates some standard and utility methods derived from the data itself.

In this article, I will share more about defaut methods created in data class.

Okey, let do it!

So we summarize, what can we do with the data class:

  • Data class stores data (of course ^^)
  • Generate get and set by itself
  • Override the hashcode (), equals () and toString () methods

And now I will go through the defaut methods in the data class

1 Copy ()

Function Copy () is not the function that creates copy or clone object. The purpose of this function is to create an object that “closely resembles” the old one. It is used in cases where we need to copy an object changing some of its properties, but keep the rest.

For example

2 ComponentN function (s)

componentN () functions correspond to properties in the order of their declaration in the class.

Order the components from left to right.

Some note :

  • The number of correctly created components is equal to the number of arguments declared in the constructor class

  • If using equals () to test 2 objects, there are only different checks against the arguments, the remaining values ​​are not calculated.

Two objects have different values, but are considered the same

Article Source: https://proandroiddev.com/kotlin-data-class-behind-the-mask-51a05ad92ae9

Share the news now

Source : Viblo