3

您好我想循环一组字符串并将它们从 String 类型转换为 ObjectId 类型。

我试过这样:

followingIds.foreach(e => e = new ObjectId(e))

但我不能做那个任务。

我也尝试使用“for”,但我不知道如何访问 Set by Index 的每个位置。

for (i <- 0 until following.size) {
   following[i] = new ObjectId(following[i])
}

这既不工作,

谁能帮我?!?请!

4

2 回答 2

12

如果您坚持可变性,则可以使用以下内容:

var followingIds = Set("foo", "bar")
followingIds = followingIds.map(e => new ObjectId(e))

但是你可以用不可变的东西让你的代码更加灵活:

val followingIds = Set("foo", "bar")
val objectIds = followingIds.map(e => new ObjectId(e))

现在变量(值)名称非常具有描述性

于 2012-12-02T20:00:23.127 回答
0

类似 Java-1.4?

val mutableSet: collection.mutable.Set[AnyRef] = collection.mutable.Set[AnyRef]("0", "1", "10", "11")
//mutableSet: scala.collection.mutable.Set[AnyRef] = Set(0, 1, 10, 11)

for (el <- mutableSet) el match { 
  case s: String  => 
    mutableSet += ObjectId(s)
    mutableSet -= s
    s
  case s => s
}

mutableSet
//res24: scala.collection.mutable.Set[AnyRef] = Set(ObjectId(0), ObjectId(11), ObjectId(10), ObjectId(1))
于 2012-12-02T21:14:22.523 回答