Here's an unlikely one. Can I cast an `Any?` objec...
# reflect
v
Here's an unlikely one. Can I cast an
Any?
object to an arbitrary
KClass
. Here's what I would like to do:
Copy code
fun Request.bind(modelClass: KClass<*>): Any? {
	return WebForm(this,modelClass).get() as modelClass
}
I'd like to avoid having to type
val person: Person = request.bind(Person::class) as Person
- that's a lot of references to
Person
in a single line of code.
d
From your example it sounds like you wnat a reified type parameter:
Copy code
inline fun <reified T> Request.bind(): T = WebForm(this, T::class).get() as T
If you really need to take in a
KClass
you can do the following:
Copy code
fun <T : Any> Request.bind(modelClass: KClass<T>): T = modelClass.cast(WebForm(this, modelClass).get())
v
Thank you. I went for the inline reified function and it worked really well.