Is there a way to identify a Kotlin data class from a regular Kotlin class? Like using reflection maybe?
A data class is a class that only contains state and does not perform any operation. The advantage of using data classes instead of regular classes is that Kotlin gives us an immense amount of self-generated code.
data class User(val name: String, val age: Int) fun main(args: Array<String>) { val u1 = User("John", 29) val u2 = u1. copy() val u3 = u1. copy(name = "Amanda") println("u1 hashcode = ${u1. hashCode()}") println("u2 hashcode = ${u2.
Data classes are the replacements of POJOs in Java. Hence, it is natural to think that they would allow for inheritance in Java and Kotlin. The inheritance of data classes in Kotlin doesn't execute well. Hence, it is advised not to use inheritance by extending the data class in Kotlin.
Basically, the difference is what they do. In summary, a Data Class is a template for Data Model, and a Work Class represent a work type or case type for instantiating and resolving work.
Since 1.1 there is an isData property on the class
MyDataClass::class.isData
Since Kotlin 1.1 use isData
property on KClass
. (docs)
Before Kotlin 1.1 you can try to use some heuristics, like check that it contains next methods:
public final copy
public final component{N}
public static copy$default
Note these implementation details could be changed in the future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With