Member-only story

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()

The copy()function creates an equal copy of the object. But we can see that they are different instances. It’s also useful when we want to have a copy with certain different properties

val song: Song = Song("Jazz", "John")
val anotherSong: Song = song.copy()
print(song == anotherSong) // true
print(song === anotherSong) // false
val nextSong: Song = song.copy(artist = "Judy")

4. componentN() which allows deconstruction

Kotlin will generate componentN functions based on the properties in primary constructors. What this means is, we can deconstruct object like so:

val song: Song = Song("Metal", "Jessica")
val (theGenre, theArtist) = song;
print(theGenre) // "Metal"
print(theArtist) // "Jessica"

Data Class Equivalent in Java

--

--

No responses yet

Write a response