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.
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.val or var.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.
Help fellow developers prepare for interviews
Sharing helps the Android community grow ๐