Kamil Kos
Kamil Kos

Reputation: 47

Type check an Any variable for Data Class

I have a class that has a constructor of type Any. I'm passing an instance of a Data Class to that constructor. How can I type check the Any variable to make sure it contains a Data Class?

What I tried so far:

private var myObject : Any

fun dataClassTypeCheck(): Boolean {
      if (myObject is KClass<*>) {return true}
      return false
    }

Upvotes: 1

Views: 1543

Answers (2)

Amir Azizkhani
Amir Azizkhani

Reputation: 1804

if you have Class<?>:

MyObjectClass::class.java.kotlin.isData

and if you have instance of class:

myObject.javaCalass.kotlin.isData

Upvotes: 0

al3c
al3c

Reputation: 1452

If you want to know if myObject has a type which is a data class then it's: myObject::class.isData.

If you want to know if myObject is a KClass object of a data class then it's: myObject.isData

Upvotes: 3

Related Questions