android - How do I create an instance of a generic type? -
i know question has been asked before haven't been able solve yet.
i trying create instance of class through generic type.
i've tried this:
class<vh>::getconstructor.call(parameter).newinstance()
but, error: i error method: callable expects 2 arguments, 1 provided.
i've tried method:
inline fun <reified vh> create(): vh { return vh::class.java.newinstance() }
however, haven't been able call because can't use generic type reified type.
this approach doesn't work:
fun <vh> generateclass(type: class<vh>): vh { return type.newinstance() }
as when call this: generateclass<vh>(class<vh>::class.java)
error: only classes allowed on left handside of class literal
.
my question in nutshell: how create instance of class generic type?
thanks in advance
you can't. unless generic type reified disappears during runtime, making unable create instance.
your example of reified function create()
works, reified type must resolved during compilation, standard generic types cannot entered reified type.
example of reified "class generating":
inline fun <reified vh : any> generateclass(): recyclerview.adapter { return object : recyclerview.adapter<vh>() { override fun onbindviewholder(vh holder, int position) { // implementation... } ... } }
Comments
Post a Comment