In this post we will discuss key differences between data class and normal class in Kotlin.
Summary of kotlin data classes
- Data classes are data holders. Used for POJO or Model classes.
- Two data class objects are easily compared using
==
operator. - Data classes are easy to log with default toString() method.
- They require at least one val or var parameter in primary constructor.
- data keyword is required before class during definition.
- default hashCode() & toString() methods readily available.
Lets try to understand this further with some code:
Normal class
class Normal(
val name: String,
val age: Int)
Data class
data class Data(
val name:String,
val age:Int)
Now we can initialise these classes.
val dataObject = Data("kotlin",1)
val normalObject = Normal("Java",2)
toString() comparision
println("Data object to string is $dataObject")
println("Normal object to string is $normalObject")
Output
Data object to string is Data(name=kotlin, age=1)
Normal object to string is Normal@12edcd21
Object comparision
val similarDataObject = Data("kotlin",1)
val similarNormalObject = Normal("Java",2)
println("Compare 2 data classes ${dataObject==similarDataObject}")
println("Compare 2 normal classes ${normalObject==similarNormalObject}")
Output
Compare 2 data classes true
Compare 2 normal classes false
componentN method
The componentN method gives you variable at Nth position in the order of definition in your data class.
println("Component1: ${dataObject.component1()} & Component2: ${dataObject.component2()}")
Output
Component1: kotlin & Component2: 1
Thank you! Happy Learning!!