如何循环访问集合并使用新值重新分配集合中的每个项目



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

我尝试了这种方式:

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

但我不能做那个分配。

我也尝试使用"for",但我不知道如何访问按索引设置的每个位置。

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

这两者都行不通,

谁能帮我?!?请!

如果你坚持可变性,你可以这样说:

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))

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

Java-1.4-like?

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))

最新更新