Pattern matching is a way of checking a value against a pattern. It is a powerful alternative to the switch
statement in Java and C/C++ and can replace if-else statements in code.
A match expression has a value, the match
keyword, and at least one case
clause. The match
keyword is used instead of the switch
statement.
import scala.util.Randomval x: Int = Random.nextInt(10)def bb() = x match {case 0 => "zero"case 1 => "one"case 2 => "two"case _ => "default case"}println(bb)
In the code above, x
is a random integer that the Random
library produces. It becomes the left operand of the match
operator, and then we define an expression with four cases. The last case, _
, is chosen when none of the cases above are matched.
In Scala, we can also use case classes in pattern matching. We will be creating an abstract Notification
superclass which has three social media apps, Facebook
, Instagram
, and Snapchat
as types of notification. This is shown below:
abstract class Notificationcase class Facebook(sender: String, title: String, body: String) extends Notificationcase class Instagram(likes:Int, comment: String) extends Notificationcase class Snapchat(sender: String, streak: Int, city: String) extends Notificationdef showNotification(notification: Notification): String = {notification match {case Facebook(sender, title, body) =>s"$sender $title on your status: $body"case Instagram(likes, comment) =>s"Your picture got $likes! likes & comment: $comment"case Snapchat(sender, streak,city) =>s"$sender sent you a snap from $city with streak: $streak"}}val fbNotification = Facebook("John", "comment","Nice pic buddy")val instaNotification = Instagram(138, "When did you get engaged?")val snapchatNotification = Snapchat("Ghufran",365,"Lahore")println(showNotification(fbNotification))println(showNotification(instaNotification))println(showNotification(snapchatNotification))
The showNotification
function takes the abstract Notification
class as its input and produces a String output. It matches the type of notification by figuring out what kind of notification this is (Facebook
, Instagram
, or Snapchat
), and then it performs the appropriate actions defined for each type.
Free Resources