Check class type of two vars

Hi everyone.

I would like to know if there is a way to do something like this:

var a: Any → get the value somewhere
var b: String = “Hello”

a::class.java is b::class.java

Actually, the only thing I can do is:

a::class.java is String

Thanks, Giovanni

a::class == b::class

@darksnake
That still won’t work at compile time.

Normally, you wouldn’t be able to do that because you already know both types so you always know it’s not true. However, a dynamic approach would be to simply do

a::class.java.isInstance(b::class.java)

Sorry. the example I did wasn’t so much correct.

I’ll provide to correct it now

It will give IDE warning. As for your sample, it checks subtyping, not equality. Also you can do it with KClass, without .java call.

a::class == b::class

is not the same check as

a is b

one is equality, the other is conformity

I tried all your response but none of them works.

I think the main problem is thath I’m checking the class type of an Any object with the class type of a var

Ok, I’ve got it.

Property to cast an Any obj to T obj:

fun Any.castTo(c: Class): T {
return this as T
}

Example:

a : Any
b : String

and then I check if a is b in this way :

if ( a.toObj(b::class.java)::class == b::class) {
//Stuff with a as String
}

Hope it will be usefull to other people