Question

I want to replace the below match with an if statement, preferably less verbose than this. I personally find if's to be easier to parse in the mind.

val obj = referencedCollection match{
            case None => $set(nextColumn -> MongoDBObject("name" -> name))
            case Some( collection) =>....}

Is there an equivalent if statement or some other method that produces the equivalent result?

Was it helpful?

Solution 2

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.

OTHER TIPS

You can replace the pattern match by a combination of map and getOrElse:

ox match {
  case None => a
  case Some(x) => f(x)
}

can be replaced by

ox.map(f).getOrElse(a)

There is huge number of options (pun intended):

if (referencedCollection != None) { ... } else { ... }
if (referencedCollection.isDefined) { ... } else { ... } // @Kigyo variant
if (referencedCollection.isEmpty) { /* None processing */ } else { ... }

You could do it like this:

val obj = if(referencedCollection.isDefined) { (work with referencedCollection.get) } else ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top