generic getCollection() for multiple type

160 views
Skip to first unread message

mail.de...@gmail.com

unread,
May 3, 2018, 9:17:18 AM5/3/18
to kmongo
I'm trying to use a BaseDao which should have some generic methods for all the child Dao (UserDao, MovieDao, etc).
So I pass the specific entity in the generic base as:


class UserDao : BaseDao<UserEntity>() { ... }

This base class implements the generic methods as follows:


open class BaseDao<T: Any>() { 
    fun get(id: String): T? {
       
return getCollection().findOneById(id)
    }

    fun save(entity: T): T {
        return getCollection().save(entity)
    }

    fun delete(id: String) {
        getCollection().deleteOneById(id)
    }
    ...
}


However, a problem occurs on getCollection() method:


private inline fun <reified T: Any> getCollection(): MongoCollection<T> {
    return MongoDb.getDatabase().getCollection<T>()
}

This gets a compilation error each time I call it:


Type inference failed: Not enough information to infer parameter T in
inline
fun <reified T : Any> getCollection(): MongoCollection<T#1 (type parameter of app.api.db.dao.BaseDao.getCollection)>
Please
specify it explicitly.


Any idea how can I achieve this generic getCollection() in BaseDao?

zigzago

unread,
May 3, 2018, 3:11:04 PM5/3/18
to kmongo
You can use reflection. In your BaseDao:

@Suppress("UNCHECKED_CAST")
private fun getDaoEntityClass(): KClass<T> =
    ((this::class.java.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<T>).kotlin

protected fun getCollection(): MongoCollection<T> =
       getDaoEntityClass().let { k ->
        MongoDb.getDatabase().getCollection(KMongoUtil.defaultCollectionName(k), k.java)
}

HTH

mail.de...@gmail.com

unread,
Jun 16, 2018, 8:32:30 AM6/16/18
to kmongo
Thank you, this works perfectly!
Reply all
Reply to author
Forward
0 new messages