Hi! I have a general question, I am trying to writ...
# announcements
f
Hi! I have a general question, I am trying to write a function that takes a class variable as a parameter and then returns a list of objects with that class, how do one do that in kotlin? I want to do this:
Copy code
fun findAll(modelClass: KClass<out BaseModel>): List<modelClass> {
  return Ebean.find(modelClass::class.java).findList()
}
But that obviously is not the right syntax
Copy code
fun <T : BaseModel> findAll(modelClass: KClass<T>): List<T> {
    return Ebean.find(modelClass::class.java).findList() as List<T>
  }
Seems to work, but it is an unchecked cast, guess Im fine with that
a
there is no way around an unchecked cast
f
Yeah I actually found that they suppress the check in the docs for kotlin, so thats what Ill do 🙂
a
do you need to use a
KClass<T>
? or would be
fun <T : BaseModel> findAll(): List<T>
be good enough?
f
But how do I then specify which class I would like to return?
Do you mean like an extension function?
a
with
val modelClasses = findAll<ModelClass>()
?
f
Oh, you can do that? that is nice
a
inline fun <reified T: BaseModel> findAll() : List<T> { .. }
same body but without the argument
and use
T::class.java
inside the body instead of
modelClass::class.java
f
Awesome!
It has to be inline? Its attached to an object called DB so I call it like this now
DB.findAll(Class::class)
right now
But I will now call it like this
DB.findAll<Class>
🙂
a
yes, if you inline the function, kotlin knows exactly what
T
is and
T::class.java
works, otherwise it doesnt
f
Yepp, did that, it is nice
Thank you 👍
a
you could even keep both methods, the new extension method just calls the old with
KClass<T>
as argument
best of both worlds 🙂