Reputation: 4709
Is there a difference between the following two ways of pattern matching:
foo match {
case a if(cond) => println("bar")
case a => println("baz")
case _ => println("default")
}
and
foo match {
case a => if (cond) println("bar") else println("baz")
case _ => println("default")
}
Upvotes: 0
Views: 96
Reputation: 39577
8.4 of the spec says evaluation of expressions may not be in textual order, which is why guards should not be side-effecting.
So if your conditional test is side-effecting, don't put it in a guard.
Upvotes: 1
Reputation: 30310
In terms of what you are trying to accomplish, there is no difference. But semantically there is a difference in what you're actually doing.
In the first case, you have a pattern with a guard suffix (the condition). The guard is evaluated only if the pattern in the case matches. If the guard expression evaluates to true, the pattern match succeeds.
In the second case, when the pattern in the case matches, a partial function is executed. Within that partial function body is a condition, and this works out like any function body with a condition inside.
Check out Section 8.4 of the Scala Language Specification for details on pattern matching. It is riveting.
Finally, note both your examples will produce errors or warnings (depending on Scala version) because the defaults are unreachable. I know it is just a contrived example, but just sayin'.
Upvotes: 3