Kotlin Data Classes: A Complete Guide with Practical Examples

In Kotlin, data classes offer a convenient way to handle classes only made to handle data. These types of data classes are called Data-centric classes. In this tutorial, we will learn about, What a data class is, how to declare a data class, and how to use a data class in Kotlin.

Kotlin Data Classes: A Complete Guide with Practical Examples

Kotlin Data Classes: A Complete Guide with Practical Examples

What is a Data class?

A data class in Kotlin is a special type of class that is designed to hold data only. Kotlin made it easy by providing a getter setter and removing all boilerplate code. To declare a data class we have to use the data keyword on class name declaration time.

Key features of Data Class:

  1. Automatically generates common functions and reduces our code.
  2. These functions are automatically generated toString(), equals(), hashCode(), copy(), and component functions.
  3. Support getter & setter without declaring.

Syntax of Data Class in Kotlin:

To define a data class we have to use the data class keyword.

Example of creating a Data class in Kotlin:

For this example, we are creating a data class to store Student information. This class has 3 properties name, age, and email.

Creating object and get data class properties without Getter:

Code explanation:

I have created a Student data class to store student name, age, and email. To retrieve the data from the student object there is no need to call the getter instead we can directly get the property value.

Creating objects and set data class properties without a Setter:

In a data class to assign values to a single property there is no need to use a setter.

Conclusion:

Data classes make our code clean and short without disrupting the functionality. So when creating classes to store data then always use data classes. Keep practicing and you will master the data classes in Kotlin.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *