Scala:添加到列表而不添加到列表

时间:2017-03-24 19:22:12

标签: mongodb scala

我正在尝试将项添加到mongo DBObject列表中,如下所示:

var retVal:Seq[DBObject] = List()

statuses.foreach(status => {
  val statusBuilder = MongoDBObject.newBuilder
  statusBuilder += "status" -> status.status
  statusBuilder += "name" -> status.name
  statusBuilder += "percentage" -> status.percentage

  retVal ++ statusBuilder.result
  retVal.++(statusBuilder.result)
})
//retVal is empty here

问题在于,尽管没有错误,但实际上没有任何内容添加到列表中。我很困惑为什么会这样。想法?

2 个答案:

答案 0 :(得分:2)

这是因为你必须分配一个列表 retVal = retVal ++ statusBuilder.result

答案 1 :(得分:1)

Why not use a .map?

val retVal: Seq[DBObject] = statuses.map{
  status => 
    val statusBuilder = MongoDBObject.newBuilder
    statusBuilder += "status" -> status.status
    statusBuilder += "name" -> status.name
    statusBuilder += "percentage" -> status.percentage

    statusBuilder.result
})