0
0
Kotlinprogramming~5 mins

Data classes for value holders in Kotlin

Choose your learning style9 modes available
Introduction

Data classes help you store and organize information easily. They automatically create useful functions like printing and comparing.

When you want to group related information like a person's name and age.
When you need to pass multiple values together in your program.
When you want to compare two sets of data quickly.
When you want to print data in a readable way without extra work.
Syntax
Kotlin
data class ClassName(val property1: Type1, val property2: Type2, ...)

Use val for read-only properties and var for mutable ones.

Data classes automatically provide toString(), equals(), and hashCode().

Examples
A simple data class to hold a person's name and age.
Kotlin
data class Person(val name: String, val age: Int)
Stores coordinates for a point in 2D space.
Kotlin
data class Point(val x: Int, val y: Int)
Title can change, author stays the same.
Kotlin
data class Book(var title: String, val author: String)
Sample Program

This program creates three people using a data class. It prints the first person's details and compares the first person with the others.

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

fun main() {
    val person1 = Person("Alice", 30)
    val person2 = Person("Bob", 25)
    val person3 = Person("Alice", 30)

    println(person1)  // Prints person1 details
    println(person1 == person2)  // Compares person1 and person2
    println(person1 == person3)  // Compares person1 and person3
}
OutputSuccess
Important Notes

Data classes must have at least one property in the primary constructor.

You can copy data classes with changes using the copy() function.

Summary

Data classes store related values simply and clearly.

They automatically create useful functions like printing and comparing.

Use them when you want easy-to-use containers for your data.