Reputation: 17
I have a question regarding casting in Kotlin. I want to cast an object that was generated by parsing JSON. The type to which it should be cast will be determined dynamically. This is causing issues which I explain in the comments in the following piece of code:
// interface for objects that are received as json
interface Bundle
// many data classes implementing the Bundle interface
// e.g.
data class DailyPostBundle(/* ... */) : Bundle
data class CreatePostBundle(/* ... */ : Bundle
// ...
val data = /*json string representing a Bundle*/
// logic:
// does this function have to @Operator annotation?
func.findAnnotation<Operator>()?.let {
// yes it does. is it the right operator?
if (it.operatorName == operator) {
// yes it is
// find the data bundle class from class path
val bundleClass = Class.forName("$bundleClassesPackage.${type}Bundle")
// now create an instance of the class from the json string
val bundle = Gson().fromJson(data, bundleClass)
// bundle is correctly parsed, BUT: it is of type <Any!>
// I want to pass it to the function,
// therefore it needs to have a type that is an implementation of Bundle,
// e.g. DailyPostBundle
// I cannot cast it explicitly here, the type to which bundle should be cast should be inferred from bundleClass
// using the dynamically located class works for parsing JSON, but it does not work for casting
func.call(bundle) // doesnt work!
// what I want to do (pseudo-code):
func.call(bundle as bundleClass) // doesnt compile!
}
}
Thank you for any suggestions
Upvotes: 1
Views: 3202
Reputation: 312
You should be able to use cast or safeCast.
func.call(bundleClass.cast(bundle))
(Update) Actually, you get a Java class object, so the correct documentation is here.
Also, to use Kotlin's safeCast, you would need to get an instance of the Kotlin class:
bundleClass.kotlin
Upvotes: 1