mongo-scala-driver最近更新了,我想更新我的应用程序(link)以支持新添加的case classes .
我目前在处理这些案例类时遇到问题,但找不到解决问题的方法(至少是正确的方法)。
我有一个名为 Collection
的特征,我在其中定义了一些可以应用于我的任何集合的通用查询:
import org.mongodb.scala.model.Filters._
import org.mongodb.scala.{MongoCollection, _}
import scala.concurrent.Future
trait Collection[T] {
protected val DEFAULT_LIMIT_SIZE = 50
protected val collection: MongoCollection[T]
def insert(obj: String): Future[_]
def get(id: Int) = collection.find(equal("_id", id)).first().head()
}
我还在子类中实现了一些特定于集合的查询,例如
import org.mongodb.scala.MongoCollection
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
object Groups extends Collection[Group] with Database {
override val collection : MongoCollection[Group] = database.withCodecRegistry(Group.codecRegistry).getCollection("groups")
override def insert(groupId: String) : Future[Group] = {
val group = Group(groupId.toLong)
collection
.insertOne(group)
.head()
.map(_ => group)
}
def all =
collection
.find()
.toFuture()
}
问题来自 Collection
特征的 get
方法:
[error] Collection.scala:13: No ClassTag available for C
[error] def get(id: Int) = collection.find(equal("_id", id)).first().head()
我很确定这是因为我使用特征类型参数作为 MongoCollection 的类型,但我想不出其他方法来实现它。
我怎样才能做到这一点?
谢谢
编辑:通过将 (implicit ct: ClassTag[T])
添加到 Collection
特性的每个方法中,它似乎可以工作,但我真的不喜欢那样做...
EDIT2:也可以将此 implicit ct
放入特征中,并从子类中覆盖它:
trait Collection[T] {
implicit def ct: ClassTag[T]
...
}
在子类中:
object Groups extends Collection[Group] with Database {
override def ct = implicitly
...
}
最佳答案
更新:您需要在集合特征的 get 方法中为 T
隐式传递 ClassTag
。
def get[T : scala.reflect.ClassTag] {
//...........
}
关于mongodb - Scala 通用 MongoDB 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43138385/