如何以递归方式附加到Casbah中的DBObject
,然后返回单个MongoDBObject
并附加每个列表元素?
请注意,以下内容无法编译或工作,但它打算显示我想要的代码
def foo( pairs: List[(String, Int)]): List[MongoDBObject] = {
def go( ps: List[(String, Int)], acc: List[MongoDBObject]): List[MongoDBObject] =
ps match {
case x :: xs if(x._1 == "BAD") => go(xs, acc)
case x :: xs => go(xs, MongoDBObject(x._1 -> x._2) :+ acc) /* error line */
case Nil => acc
}
}
val pairsList: List[MongoDBObject] = foo( getPairs() ) // assume getPairs() is defined
val builder = // do something to convert pairsList -> MongoDBObject (maybe a fold?)
val results = collection.find(builder)
当我尝试上述内容时,我在第二个案例陈述中看到了以下编译时错误。
[myApp] $ compile
[info] Compiling 1 Scala source to ...
[error] c:\development\myApp\Test.scala:85: overloaded method value apply with alternatives:
[error] [A(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply) <
: String, B(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)](e
lems: List[(A(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply),
B(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply))])com.mongo
db.casbah.commons.Imports.DBObject <and>
[error] [A(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply) <
: String, B(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)](e
lems: (A(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply), B(in
method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply))*)com.mongodb.ca
sbah.commons.Imports.DBObject
[error] cannot be applied to (com.mongodb.casbah.query.Imports.DBObject with com.mongodb.casbah.query.dsl.QueryExpressionObject)
[error] go(xs, acc :+ MongoDBObject(elemMatch))
[error] ^
[error] one error found
答案 0 :(得分:2)
如果要将新对象附加到列表中,则应执行此操作:
MongoDBObject(x._1 -> x._2) :: acc