简体   繁体   中英

Scala implicit class

I am seeing some unexpected behavior with an implicit class. I have a case class that is retrieved from Mongo, and in certain cases wrapped into an implicit class with convenience lazy vals to retrieve data from other relevant collections. Code looks something like

case class MyClass(
    _id: UUID, ...,
    //some fields
)

and then

object MyImplicits {

    implicit class MyRichClass(c: MyClass){
        lazy val field1: Future[Iterable[T1]] = db.findAll[T1](bson)
        lazy val field2: Future[Iterable[T2]] = db.findAll[T2](bson)
    }

}

and the conversion is used like

import ...MyImplicits.MyRichClass
val c: MyClass...
c.field1.map(...)

My problem is Futures in field1 and field2 always contain an empty Iterable. I have spent best part of today debugging my queries, and they work correctly both in test code and Mongo cli.

Any tips would be greatly appreciated.

I have a wrapper around org.mongodb.scala.MongoClient, that has:

/**
* Finds all instances of T using raw mongo query
*
* @param bson search query
* @tparam T
* @return
*/
private[service] def findAll[T: ClassTag](bson: Bson): Future[Iterable[T]] = {
    val colName = resolveCollection[T]
    logger.info("colName = " + colName)
    db.getCollection[T](colName).find(equal("ownerId", "user1")).toFuture().map(t => {
      logger.info("t = " + t)
      t
    })
}


/**
* Returns collection name for given type
* @tparam T
* @return
*/
private def resolveCollection[T: ClassTag]: String = {
scala.reflect.classTag[T] match {
  case `...tag` => "collectionName"
  ....
}

}

The

 equal("ownerId", "user1")

is hardcoded for debugging purposes, as well as extra loggers.

There is actually no issues with the code. I was literally querying a wrong database, so, yes - all collections were in fact empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM