A Practical Guide to Kotlin Data Class — With Examples

Wei Hung
3 min readFeb 7, 2021

TL; DR: Data class reduces boilerplate code by automatically providing getter/setter, hashcode, equals, toString, and componentN methods.

Kotlin provides a special type of class known as the data class, which has a prefix with the data keyword. An example of a data class is as below:

data class Song(val genre: String, val artist: String)

When to use Kotlin data class?

When we want to include the object properties in getter/setter, hashcode()/equals(), toString() and copy() functions, we can use a data class.

Only object properties declared in the primary constructor will be used.

With Song as our data class example, all of its properties in the primary constructor ( i.e.genre, artist) are automatically used for :

  1. hashcode()/equals()
val songA: Song = Song("Country", "Jim")
val songB: Song = Song("Country", "Jim")
val isEqual = songA.equals(songB) // true

2. toString()

val song: Song = Song("EDM", "Jessie")
print(song.toString()) // "Song(genre=EDM, artist=Jessie)"

3. copy()

--

--

No responses yet