What is Data Class in Kotlin: Simple Explanation and Example
data class in Kotlin is a special class designed to hold data. It automatically provides useful functions like toString(), equals(), and hashCode() so you don't have to write them yourself.How It Works
A data class in Kotlin is like a simple container for data, similar to a box where you keep related items together. When you create a data class, Kotlin automatically creates some helpful functions for you. These include toString() to show the data as text, equals() to compare two objects, and hashCode() for using objects in collections.
Think of it like a form you fill out: the data class holds the answers, and Kotlin gives you tools to easily check, print, or compare those answers without extra work. This saves time and reduces mistakes compared to writing all these functions yourself.
Example
This example shows a simple data class called Person with two properties: name and age. Kotlin automatically creates useful methods for this class.
data class Person(val name: String, val age: Int) fun main() { val person1 = Person("Alice", 30) val person2 = Person("Alice", 30) println(person1) // Prints the data in a readable way println(person1 == person2) // Checks if data is equal }
When to Use
Use a data class when you need to store and manage simple data without complex behavior. They are perfect for representing things like user profiles, settings, or any group of related values.
For example, if you are building an app that handles contacts, a data class can hold each contact's name, phone number, and email. This makes your code cleaner and easier to maintain because Kotlin handles common tasks automatically.
Key Points
- Data classes automatically generate
toString(),equals(),hashCode(), andcopy()functions. - They must have at least one property in the primary constructor.
- They are ideal for simple data holding without extra logic.
- Using data classes reduces boilerplate code and errors.