ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Kotlin Tutorial• 7 min read

Classes, Properties & Data Classes

Primary constructors, automatic copy(), toString(), equals() & hashCode()

Kotlin properties bundle fields and getters/setters automatically. data class automatically generates equals(), hashCode(), toString(), and copy().

The Power of data class

In Java, a basic POJO requires ~50 lines of boilerplate for getters, setters, equals, hashCode, and toString.

In Kotlin, prefixing with data class User(val id: Int, val name: String) provides all of that in exactly 1 line.

The .copy() method allows creating modified clones of immutable objects effortlessly.

One-Line Data Class and Immutable Copy
data class Student(val id: Int, val name: String, val gpa: Double)

fun main() {
    val s1 = Student(101, "Alan", 3.8)
    println(s1) // Student(id=101, name=Alan, gpa=3.8)

    // Immutable cloning with copy()
    val s2 = s1.copy(gpa = 4.0)
    println(s2) // Student(id=101, name=Alan, gpa=4.0)
    
    // Automatic value equality (== checks content, not memory address!)
    println(s1 == s2) // false
}
data class automatically implements value-based equality and copy.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What does the `data` modifier in `data class` automatically generate for you in Kotlin?