user79074
user79074

Reputation: 5270

scala match expression avoiding code duplication

Say I am using a match expression to test a value that may or may not be in a Map object as follows:

map.get(key) match {
  case Some(value) if (cond1(value)) => res1(value)
  case Some(value) if (cond2(value)) => res2()
  case None => res2()
  case _ => // None of the above
}

As you can see I want to call the res2 in either case where I have a value for my key and it meets condition 2 or I have no value for key. Can anyone suggest a better construct that would avoid the duplicate calls to res2() in the sample above?

Thanks Des

* Sorry I realised that the code sample was not quite correct and have updated accordingly. I only want to call res2 in the case where the value for the key meets cond2 OR there is NO entry for key.

Upvotes: 0

Views: 188

Answers (2)

Ed Staub
Ed Staub

Reputation: 15690

I believe what you want is:

map.get(key) match {
  case Some(value) if (cond1(value)) => res1(value)
  case o: Option[String] if ( o.forall(cond2) ) => res2()
  case _ => 
}

replacing [String] with whatever the type of key is.

The names of the methods on Option aren't always the most obvious; in maintaining functional purity they sacrifice clarity for us illiterati. In this case, the scaladoc for Option tells us that forall:

Returns true if this option is empty or the predicate p returns true when applied to this scala.Option's value.

Upvotes: 1

igr
igr

Reputation: 3499

Without gard if that are only possibilities:

case Some(value) => if (cond1(value) ) res1(value) else res2()

Upvotes: 0

Related Questions