2013-10-15 38 views
0

如何遞歸追加到Casbah中的DBObject,然後返回單個MongoDBObject並附加每個列表元素?遞歸構建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) 

當我試圖像上面,我看到了下面的編譯時錯誤在我的第二個case語句。

[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 

回答

2

如果你想在新對象追加到列表這個應該這樣做:

MongoDBObject(x._1 -> x._2) :: acc 
+0

在我的情況,我想'去(XS,MongoDBObject(elemMatch):: ACC)',但是我得到了上面的同樣的錯誤。 'elemMatch'是有效的,因爲你之前幫助我創建了它。 –

+0

'MongoDBObject(「a」 - >「b」):: List(MongoDBObject(「c」 - >「d」))'適用於我。也許需要澄清一些。 – Ross