Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - cast to Class<T> or to KClass<T>

Tags:

kotlin

In Kotlin I can cast Any to another type like so

val obj: Any = 123
val num: Int = obj as Int

In my case I want to be able to either cast to Class<Int> or KClass<Int>, something like...

val obj: Any = 123
val kotlinClass = Int::class
val javaClass = Int::class.java

val num : Int = obj.castTo(kotlinClass)
val num2: Int = obj.castTo(javaClass)

How exactly can this be achieved?

like image 586
Matthew Layton Avatar asked Oct 12 '25 02:10

Matthew Layton


1 Answers

Try it the other way around, i.e. using the class to cast the object:

val num : Int = kotlinClass.cast(obj)
val num2 : Int = javaClass.cast(obj)

Be sure to add kotlin-reflect as a library, if you really require KClass.cast. Alternatively you may also be interested in KClass.safeCast.

like image 69
Roland Avatar answered Oct 15 '25 23:10

Roland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!