Functional Programming: Pattern Matching

For developers coming to Scala from Java, pattern matching is a very powerful, flexible alternative to using if for conditional logic. In practice it allows for very clean, terse blocks of conditional code.
Let us take an example:

Java

  if (response.isSuccessful()) {
    if (user.isBasketEmpty()) {
      forwardUser("/welcome");
    } else {
      forwardUser("/basket");
    }
  } else {
    forwardUser("/failedLogin");
  }

Scala

response.isSuccessful match {
  case true if (user.isBasketEmpty) => forwardUser("/welcome")
  case true  => forwardUser("/basket")
  case false  => forwardUser("/failedLogin")
}

So what is happening with the Scala version? We are matching on the result of calling isSuccessful. We do not need brackets to call this method so it is ‘isSuccessful’ not ‘isSuccessful()’.

First case: the value of this is matched against true. If it is true we provide a caveat, we also want to check user.isBasketEmpty is true. If both criteria are met we will forward the user to ‘/welcome’.

Second case: This is just checking response.isSuccessful but if the user.isBasketEmpty returns false.

Third case: This is the more explicit way of catching when response.isSuccessful is false, an alternative would be

case _ => forwardUser("/failedLogin")

Where the underscore acts as a wildcard, in this case being a catch-all.

Advertisements

One thought on “Functional Programming: Pattern Matching

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s