Reputation: 569
As in most languages, Scala has an if
statement. However, using pattern matching I can achieve the exact (?) same result using code of the form:
(condition) match {
case true => { /* handle the true case */ }
case false => { /* handle the false case */ }
}
This feels like an abuse of the mechanism, but I find it hard to explain why. Can wiser heads help me understand the position?
Upvotes: 2
Views: 251
Reputation: 12102
The match compiles to the equivalent of
val scrutinee = condition
if (scrutinee == true) /* handle success case */
else if (scrutinee == false) /* handle failure case */
else throw new MatchException()
so it's semantically identical. But why would you? It's more verbose, more syntax-heavy, and less clear than the if
expression.
Upvotes: 4
Reputation: 179119
I wouldn't normally use it, although yes, it's a matter of taste. But there are cases where I might resort to this construction. For example when I need to send as argument a higher order function that reveives a Boolean
value (using Scala's PartialFunction
syntax):
future.onSuccess {
case true => ???
case false => ???
}
Or when there are extra conditions, something along these lines:
value match {
case true if condition1 => ???
case true if condition2 => ???
case true if condition3 => ???
case false => ???
}
Upvotes: 4