Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? Like using reflection maybe?

like image 386
Ragunath Jawahar Avatar asked Mar 16 '15 05:03

Ragunath Jawahar


People also ask

What is the difference between Kotlin data class and normal class?

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.

How do you get data from Kotlin data class?

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.

Can data class inherit Kotlin?

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.

What is difference between class and data class?

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.


2 Answers

Since 1.1 there is an isData property on the class

MyDataClass::class.isData
like image 120
Jake Coxon Avatar answered Oct 22 '22 16:10

Jake Coxon


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.

like image 42
bashor Avatar answered Oct 22 '22 16:10

bashor