Data Class in Kotlin

Data Class in Kotlin is used when the class is intended to represent a complex model that contains only properties(may be belonging to different data types) and the objects of the class are required to hold only the properties’ values(data). Classes that hold only data, hence Data Classes.

Also, Data classes are useful when a function has to return more than one value. All the values that are required to be returned are encapsulated in a data class and the object of data class is returned.

The structure of data class is similar to that of a usual kotlin class, except that the keyword   data   preceeds the keyword    class   .

An example of Data Class in Kotlin

In the below example we shall define a data class “Book” with variables “name” and “price“. And add objects of Book to an array of Book, and finally print them.

The default values (name=””, price=0) are provided in the definition of data class.

Output :

Copy existing Data Class object to a new variable with some of the parameters modified

Kotlin allows to copy an existing data class object to a new variable as is or with modifications to some of the parameters of Data Class.

Following example demonstrates the copy functionality of a data class object :

book1, book2 are new objects created
book3 is a copy of book1
book4 is a copy of book2 with name modified to “The Last Bond”
book5 is a copy of book2 with price modified to 263

Output :

Access properties of a data class using component functions

To access individual properties of a data class, component functions are used. An example is provided below, where we access the properties, “name” and “price” of data class “Book”.

Output :

Conclusion :

In this tutorial, we have learnt what a data class in Kotlin is, how to initialize an object of data class, how to copy one object to other with some properties(or you can say parameters) modified, and also to access the individual parameters of data class using component functions.