You probably ought not indulge yourself in continuing to use if
in conditions like this. It's not idiomatic, rarely is faster, is more verbose, requires intermediate variables so is more error-prone, etc..
Oh, and it's a bad idea to use anything with $
signs!
Here are some other patterns that you might use in addition to match:
val obj = referenceCollection.fold( $set(nextColumn -> MongoDBObject("name" -> name) ){
collection => ...
}
val obj = (for (collection <- referenceCollection) yield ...).getOrElse{
$set(nextColumn -> MongoDBObject("name" -> name)
}
val obj = referenceCollection.map{ collection => ... }.getOrElse{
$set(nextColumn -> MongoDBObject("name" -> name)
}
You can basically think of map
as the if (x.isDefined) x.get...
branch of the if
and the getOrElse
branch as the else $set...
branch. It's not exactly the same, of course, as leaving off the else
gives you an expression that doesn't return a value, while leaving off the getOrElse
leaves you with an unpacked Option
. But the thought-flow is very similar.
Anyway, fold
is the most compact. Note that both of these have a bit of runtime overhead above a match
or if
statement.