Is it possible to use a variable in the right hand side of Kotlin’s type casting “is” operator?

Issue

Is the below intended operation be achieved in any (common) way in Kotlin?

val dataClass  String::class
if (anotherObject is dataClass) { ... }

I would want to know if it is possible to check for type casting with a variable on the RHS of the is operator. Also any other way of doing this?

There is some concept here that I may have not understood and eventually ended up asking this question here. Please do share any info related to this.

Solution

Use KClass.isInstance:

Returns true if value is an instance of this class on a given platform.

val dataClass  String::class
val anotherObject: Any  ""
if (dataClass.isInstance(anotherObject)) {
    println("anotherObject is String!")
}

Note that unlike is, the type of anotherObject will not become String inside the if statement, because the compiler does not know what class is inside dataClass.

Answered By – Sweeper

Leave a Comment