🚀 Enrollments Open for Jetpack Compose Cohort 2 — 7 Days of Live Learning to Build Modern Android UIs 💚Join Now
KotlinIntermediate4 min
What is Data Class in Kotlin?

Answer

A Data Class in Kotlin is a class whose main purpose is to hold data. The compiler automatically derives standard functionality from the properties declared in the primary constructor.

Key Features

When you mark a class as `data`, Kotlin automatically generates:

  1. `equals()` / `hashCode()`: For comparing object content.
  2. `toString()`: Prints a readable string like `User(name=John, age=30)`.
  3. `copy()`: Creates a copy of the object with some properties modified.
  4. `componentN()` functions: Enables destructuring declarations.

Requirements

  • The primary constructor must have at least one parameter.
  • All primary constructor parameters must be marked as `val` or `var`.
  • Data classes cannot be abstract, open, sealed, or inner.

Example

```kotlin data class User(val name: String, val age: Int)

fun main() { const user1 = User("Alice", 25) const user2 = user1.copy(age = 26) // Copy with modification

println(user1) // User(name=Alice, age=25)

// Destructuring
const (name, age) = user1
println("$name is $age years old")

} ```

Want to master these concepts?

Join our live cohorts and build production-ready Android apps.

Accelerate Your Growth

Don't just learn concepts in isolation. Build production-ready Android apps with expert guidance.

Live Interactive Sessions
Code Reviews & Feedback
Real-world Projects
Career Guidance

Limited seats available for next cohort