0
0
Android Kotlinmobile~5 mins

Data classes in Android Kotlin

Choose your learning style9 modes available
Introduction

Data classes help you store and manage data easily without writing a lot of code.

When you want to group related information like a person's name and age.
When you need to pass simple data between parts of your app.
When you want Kotlin to automatically create useful functions like equals() and toString() for your data.
When you want to keep your code clean and easy to read.
Syntax
Android Kotlin
data class ClassName(val property1: Type, val property2: Type)

Use data keyword before class to create a data class.

Properties are usually declared in the primary constructor.

Examples
This creates a data class User with two properties: name and age.
Android Kotlin
data class User(val name: String, val age: Int)
A simple data class to hold coordinates.
Android Kotlin
data class Point(val x: Int, val y: Int)
Data class with three properties to store book details.
Android Kotlin
data class Book(val title: String, val author: String, val year: Int)
Sample App

This program creates two Person objects and prints their details. The toString() function is automatically created for data classes, so printing person1 shows its properties.

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

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

  println(person1)
  println("Name: ${person2.name}, Age: ${person2.age}")
}
OutputSuccess
Important Notes

Data classes automatically generate equals(), hashCode(), toString(), and copy() functions.

All primary constructor parameters need to be marked as val or var.

Data classes cannot be abstract, open, sealed, or inner.

Summary

Data classes make storing and handling data simple and clean.

Kotlin creates useful functions for you automatically.

Use data classes when you want to group related data together.