Computer Science

class vs data class


• class, General purpose class definition (can be used for any business logic, functions, etc.).
• data class, Classes used specifically to hold data.

data class

When you define a data class, Kotlin automatically generates the following: equals() → Checks the equality of objects based on their content. hashCode() → Works correctly in hash tables (map, set). toString() → Converts the object to a nicely formatted string. copy() → Allows you to copy the object and modify some fields. componentN() → For destructuring declarations (e.g., val (id, name) = user) These are not automatically provided in the standard class; you must write them yourself if you wish.

class example
                        class Musteri(val id: Int, val isim: String)
val m1 = Musteri(1, "Ali")
val m2 = Musteri(1, "Ali")

println(m1 == m2)  // false (because the reference compares)
println(m1.toString())  // com.example...                  
                    
                    

data class example
                        data class Musteri(val id: Int, val isim: String)
val m1 = Musteri(1, "Ali")
val m2 = Musteri(1, "Ali")

println(m1 == m2)  // true (comparing by content)
println(m1.toString())  // Musteri(id=1, isim=Ali)
println(m1.copy(isim = "Veli")) // Musteri(id=1, isim=Veli)
val (id, isim) = m1  // destructuring
println(id) // 1
println(isim) // Ali