Kotlin Data Class

Kotlin Data Class is used when the class is intended to represent a complex model that contains only properties(maybe belonging to different data types) and object of the class is 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 precedes the keyword class.

Example – Kotlin Data Class

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.

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

Kotlin allows copying 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

Access properties of a Kotlin 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”.


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