Varun Muralidharan
Varun Muralidharan

Reputation: 141

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

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.

Upvotes: 1

Views: 339

Answers (1)

Sweeper
Sweeper

Reputation: 271040

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.

Upvotes: 4

Related Questions