0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This is the best answer if the OP is not expecting side effects from cond2, which (s)he shouldn't.
The OP updated his question and made this answer invalid: he wants to call res2() if the value associated with key matches cond2, or there is no value associated with key. This answer will also call it if there is a value associated with key that matches neither cond1 nor cond2.
@user79074 Answer updated to match updated question.
0

Without gard if that are only possibilities:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.