Kotlin: Data Class
28th March 2021
Data classes offer a quick and easy way to make a class which stores data.
If you want to do this in java you need to override the following methods:
toString()
equals()
hashCode()
In Kotlin however, these are auto-generated from the properties in the primary constructor.
Values not in the primary constructor are not referenced in these methods so would require you create
your own implementation.
Requirements for data classes
* The primary constructor needs to have at least one paramater
* All paramaters need to be either val
or var
* They can't be abstract, open or inner
Useful stuff
It is generally recommended that your data classes should be immutable. To make it easier to work with immutable
objects Kotlin generates the copy()
method which allows us to copy/clone the object and
change some of its properties
val nextBlogPost = kotlinDataClasses.copy(title = "RecyclerView", rating = "2/5")
If you don't want something to be used in the auto-generated methods then you can declare it inside the body of the class
data class BlogPost(val title: String,) {
val author = "Hoinzey"
}