https://kotlinlang.org logo
#reflect
Title
# reflect
v

v79

04/12/2018, 6:40 PM
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

diesieben07

04/14/2018, 7:53 PM
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

v79

04/15/2018, 7:03 AM
Thank you. I went for the inline reified function and it worked really well.
2 Views