Is there a way to identify a Kotlin data class from a regular Kotlin class?

Is there a way to identify a Kotlin data class from a regular Kotlin class? How, for example, the use of reflection?

+7
reflection metaprogramming kotlin data-class
source share
2 answers

Starting with 1.1, the isData property exists in the class

MyDataClass::class.isData 
+3
source share

You cannot read data annotation with reflection because it has a default hold ( CLASS ).

You can try to use some heuristics, for example, check that it contains the following methods:

  • public final copy
  • public final component{N}
  • public static copy$default

But note that some of them are implementation details and are subject to change in the future.

+5
source share

All Articles