kotlin
  1. kotlin-data-class

Kotlin Data Class

In Kotlin, a data class is a class that is generally used to hold data which represents a concept or an entity. It is used to reduce the boilerplate code for creating objects that need to hold data.

Syntax

A sample syntax of a data class is as follows:

data class Person(val name: String, val age: Int)

Here, Person is the name of the data class, and name and age are the properties of the class.

Example

Let's take an example of a data class named User with two properties username and age:

data class User(val username: String, val age: Int)

Output

When creating an object of a data class, you can use the properties of the class to access and modify the data:

val user = User("JohnDoe", 32)
println("Username: ${user.username}, Age: ${user.age}")

The output will be:

Username: JohnDoe, Age: 32

Explanation

Data classes provide a simple and concise way to create classes that are meant to hold data. When a class is annotated with the data keyword, Kotlin compiler provides the following features automatically:

  • equals() and hashCode() methods
  • toString() method
  • componentN() methods (corresponding to the properties in their order of declaration)
  • copy() method

This leads to a reduction in boilerplate code, making it easier to create and use classes that hold data.

Use

Data classes are very useful when dealing with data that needs to be represented in a structured manner. They are widely used in many contexts, such as:

  • Representing database records
  • Describing JSON objects
  • Defining POJO (Plain Old Java Object) classes

Important Points

  • All primary constructor parameters must be marked as val or var.
  • A data class cannot be abstract or open.
  • A data class must have at least one primary constructor parameter.
  • Data classes automatically generate appropriate equals(), hashCode(), and toString() methods.

Summary

In this tutorial, we discussed Kotlin data classes and their syntax, example, output, explanation, use, and important points. Kotlin data classes provide a concise way to create classes that hold data and reduce boilerplate code. Understanding Kotlin data classes is essential for creating efficient and maintainable code in Kotlin.

Published on: