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:
- `equals()` / `hashCode()`: For comparing object content.
- `toString()`: Prints a readable string like `User(name=John, age=30)`.
- `copy()`: Creates a copy of the object with some properties modified.
- `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")
} ```
1:1 Mentorship
Get personalized guidance from a Google Developer Expert. Accelerate your career with dedicated support.
Personalized Learning Path
Mock Interviews & Feedback
Resume & Career Guidance
Share & Help Others
Help fellow developers prepare for interviews
Sharing helps the Android community grow 💚