Reputation: 4515
How do I make these line of codes more scala-ish (shorter?). I still get the Java feeling in it (which I want to stay away from). Thanks in advance!
import scala.collection.mutable
val outstandingUserIds: mutable.LinkedHashSet[String] = mutable.LinkedHashSet[String]()
val tweetJson = JacksMapper.readValue[Map[String, AnyRef]](body)
val userObj = tweetJson.get("user")
tweetJson.get("user").foreach(userObj => {
userObj.asInstanceOf[Map[String, AnyRef]].get("id_str").foreach(idStrObj => {
if (outstandingUserIds.exists(outstandingIdStr => outstandingIdStr.equals(idStrObj))) {
outstandingUserIds.remove(idStrObj.asInstanceOf[String])
}
})
})
Upvotes: 0
Views: 82
Reputation: 9309
One thing you want to do in Scala is take advantage of type inference. That way, you don't need to repeat yourself on the LHS:
val outstandingUserIds = mutable.LinkedHashSet[String]()
You also don't need the inner braces after the closure variable userObj =>
. Instead, use braces after foreach {} to execute multiple statements:
tweetJson.get("user").foreach { userObj =>
}
In fact, you could use the anonymous variable '_' and say:
tweetJson.get("user").foreach {
_.get("id_str").foreach ...
}
Scala encourages the use of immutable collections. One way to simplify the above even further would be to use collect
(instead of exists
+delete
) which would return a new collection with only the elements you want.
Upvotes: 1