Scala通用MongoDB集合
最近更新了,我想更新我的应用()以支持新添加的 我目前在这些案例类中遇到了一个问题,并且没有找到解决它的方法(至少是正确的方法) 我有一个名为Scala通用MongoDB集合,mongodb,scala,Mongodb,Scala,最近更新了,我想更新我的应用()以支持新添加的 我目前在这些案例类中遇到了一个问题,并且没有找到解决它的方法(至少是正确的方法) 我有一个名为Collection的特性,在该特性中,我定义了一些可以应用于我的任何集合的通用查询: import org.mongodb.scala.model.Filters._ import org.mongodb.scala.{MongoCollection, _} import scala.concurrent.Future trait Collectio
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()
}
问题来自集合的get
方法:
[error] Collection.scala:13: No ClassTag available for C
[error] def get(id: Int) = collection.find(equal("_id", id)).first().head()
我很确定这是因为我使用trait-type参数作为MongoCollection的类型,但是我想不出其他方法来实现这一点
我怎样才能做到这一点
谢谢
编辑:通过将(隐式ct:ClassTag[T])
添加到集合的每个方法
trait,它似乎可以工作,但我真的不喜欢这样做
EDIT2:也可以将此隐式ct
放在trait中,并从子类重写它:
trait Collection[T] {
implicit def ct: ClassTag[T]
...
}
在子类中:
object Groups extends Collection[Group] with Database {
override def ct = implicitly
...
}
更新:您需要在集合特征的get方法中隐式传递ClassTag
forT
def get[T : scala.reflect.ClassTag] {
//...........
}
我想这里可能是答案或者至少是提示->谢谢,我也看到了这篇文章,但我不认为它离我要找的东西太近了。事实上,在我的例子中,mongoDb的find
方法需要一个ClassTag
作为隐式def find[C]()(隐式e:C DefaultsTo TResult,ct:ClassTag[C])
,但是对于泛型tun没有可用的ClassTag,幸运的是,我不能这样做,因为traits的类型参数不能有界,ClassTag是隐式传递的,集合[T:scala.reflect.ClassTag]与集合[T]相似(隐式ct:scala.reflect.ClassTag[T])这不是scalac
告诉我的:[error]Collection.scala:7:traits不能具有具有上下文边界的类型参数
:…”也不能具有视图边界我没有意识到,您应该尝试将隐式类标记传递给方法,正如我在答案中更新的那个样。不管怎样,我很高兴你找到了解决办法。