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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With