1

I am looking for a way to do pattern matching based on the result of a function evaluation rather than the type of the val. For example,

def f1(x:String):Boolean = if (x contains ("Helllo")) true else false
val caller="Hello"

caller match 
{
  case f1(caller) => println ("caller said hello")
  case _ => println ("caller did not say hello")
}

any idea ?

2
  • It sounds like you basically want the equivalent of Haskell's ViewPatterns extension. Commented Sep 7, 2013 at 16:06
  • I get what u mean, but if it is only strings then u cna probably use regex for pattern matching. Commented Sep 7, 2013 at 16:29

2 Answers 2

2

You want to use pattern guards:

caller match 
{
  case x if f1(x) => println ("caller said hello")
  case _ => println ("caller did not say hello")
}
Sign up to request clarification or add additional context in comments.

1 Comment

thank you so much @wingedsubmariner did not even know that pattern guards existed. Thanks again.
0

I would prefer to do it without guard, that would a bit faster and cleaner:

f1(caller) match {
  case true => ....
  case false => ....
}

but for Boolean better to use if/else expression, that would be cleaner in byte code and a bit faster

1 Comment

The advantage of guards afaik is they need not be applied to all cases at once.

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.