Reputation: 401
Hi I want to loop a set of Strings and convert them from String type to ObjectId type.
I tried this way:
followingIds.foreach(e => e = new ObjectId(e))
But I cant do that assignement.
I also tried using "for" but I don't know how to access each position of the Set by Index.
for (i <- 0 until following.size) {
following[i] = new ObjectId(following[i])
}
This neither work,
Can anyone help me?!? Please!
Upvotes: 3
Views: 3158
Reputation: 1713
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))
Upvotes: 0
Reputation: 62835
If you insist on mutability you can go with something like this:
var followingIds = Set("foo", "bar")
followingIds = followingIds.map(e => new ObjectId(e))
But you can make your code more scalish with immutable things:
val followingIds = Set("foo", "bar")
val objectIds = followingIds.map(e => new ObjectId(e))
Now variables (values) names are pretty descriptive
Upvotes: 12