androidengineers.Book a session
โ† All interview questions
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

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")
}

Mark this when you can explain the answer in your own words.

Share & Help Others

Help fellow developers prepare for interviews

Sharing helps the Android community grow ๐Ÿ’š

Keep practising