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
Only object properties declared in the primary constructor will be used.
Song as our
data class example, all of its properties in the primary constructor ( i.e.
artist) are automatically used for :
val songA: Song = Song("Country", "Jim")
val songB: Song = Song("Country", "Jim")val isEqual = songA.equals(songB) // true
val song: Song = Song("EDM", "Jessie")
print(song.toString()) // "Song(genre=EDM, artist=Jessie)"
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) // falseval 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
With just a single line of code,
data class provides us all the functionalities and behaviours above. In Java, a
Song class with similar behaviours would look like this:
Useful tricks and tips
If we want to exclude any property from being included in the automatically generated functions, we can put the property in the class body :
artist properties will be used in the implementation of
It is recommended to use
finalin Java) for the properties declared in the primary constructor for the data class to be immutable
We can of course have
var in the primary constructor properties as well but this would make data class mutable.
data class Song(val genre: String, val artist: String, var title: String)val songA: Song = Song("Pop", "Jamie", "To the moon")
songA.title = "To the sun"
Gotchas and things to take note
dataclass cannot be
- At least 1 parameter is required in the primary constructor.
dataclass does not implement
dataclass can implement interfaces and extend other classes (since v1.1).
If you find this post helpful, help others to see it by giving some claps 👏