https://kotlinlang.org logo
#getting-started
Title
# getting-started
f

frank

01/07/2022, 6:35 PM
I'm developing with MongoDB and I'm creating a common class for the connection to DB. I was having trouble implementing getCollection() generic method but I succeeded. I'm looking for advice or alternatives to my approach. GetCollection() Method:
Copy code
inline fun <reified T> getCollection(collection: String): MongoCollection<T> {
  return database.getCollection(collection, T::class.java)
}
Full Code:
Copy code
open class Connection<T> {
  constructor(){
    startMongoDB()
  }

  val client by lazy { KMongo.createClient()  }
  val database by lazy { getDB() }

  fun getDB(): MongoDatabase {
    return client.getDatabase(DB_NAME)
  }

  inline fun <reified T> getCollection(collection: String): MongoCollection<T> {
    return database.getCollection(collection, T::class.java)
  }

  private fun startMongoDB() {
    client
    database
  }
}
k

Klitos Kyriacou

01/10/2022, 10:17 AM
Maybe there's something I don't quite understand, but what is the point of those two lazily constructed properties which you construct in the class's constructor (and therefore are not really lazy at all)?
s

Stephan Schroeder

01/10/2022, 11:04 AM
I don't even think Connection needs to be generic or open 🤔 How about:
Copy code
class Connection {
  private val client = KMongo.createClient()
  val database = client.getDatabase(DB_NAME)
}

inline fun <reified T> Connection.getCollection(collection: String): MongoCollection<T> =
    this.database.getCollection(collection, T::class.java)
and there is a point to be made that maybe the function should be called directly on
Database
instead of on
Connection
, so maybe even
Copy code
inline fun <reified T> Database.getCollection(collection: String): MongoCollection<T> =
    this.getCollection(collection, T::class.java)
f

frank

01/11/2022, 12:40 AM
but what is the point of those two lazily constructed properties which you construct in the class's constructor (and therefore are not really lazy at all)?
I don't even think Connection needs to be generic or open
Thx, for the tips. Yes, I already had some corrected in my second revision of the code.
My last change implementing Coroutines:
Copy code
class Connection {
  private val client = KMongo.createClient().coroutine
  val database = client.getDatabase(DB_NAME)
  val session = GlobalScope.async(start = CoroutineStart.LAZY) { client.startSession() }
  
  inline fun <reified T : Any> getCollection(collection: String): CoroutineCollection<T> {
    return database.getCollection(collection)
  }
}
9 Views