2

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?

Jeffrey Chung
  • 19,319
  • 8
  • 34
  • 54
Andy
  • 523
  • 6
  • 20
  • 1
    Seems to be similar q to https://stackoverflow.com/questions/7986641/pattern-matching-with-guards-vs-if-else-construct-in-f to which the answer is 'it depends' but pattern matching preferred. – Andy Dec 08 '17 at 11:53
  • Match as switch: http://alvinalexander.com/scala/using-match-expression-like-switch-statement – cchantep Dec 08 '17 at 12:36

2 Answers2

4

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 => ???
}
Ionuț G. Stan
  • 176,118
  • 18
  • 189
  • 202
4

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.

Martijn
  • 11,964
  • 12
  • 50
  • 96