How to Use Scala Pattern Matching
Matching with Case Classes

Besides matching against the value of an object itself, we can also match against possible types (or case class ).

Let’s say we are writing a classification program for a computer scanner at a fresh produce department of a supermarket. The scanner will label an item based on its type, e.g. fruit or vegetable. I’d imagine this is how we would define our trait and case classes.

trait GroceryItem



case class Fruit(name: String) extends GroceryItem



case class Vegetable(name: String) extends GroceryItem

Now, we are going to write a function that will take a GroceryItem object as its input and classify whether it is a Fruit or a Vegetable . This is how it would be written in its simplest form.

def classifyGroceryItem(item: GroceryItem): Unit =

item match {

case _: Fruit => println("label item as fruit.")

case _: Vegetable => println("label item as vegetable.")

case _ => println("unable to label the item. this seems to be an item for other department.")

}

Notice the syntax _: Fruit . This is how we should write our case when we want to pattern match against its instance type. Additionally, this expression does not actually look into the value of the case class ’ field (e.g. name ).

If we want to also match against the field of the case class, this is how we can do it (look at the first case expression).

def classifyGroceryItem(item: GroceryItem): Unit =

item match {

case Fruit(name) if name == "apple" => println("item is a fruit and it's an apple.")

case _: Fruit => println("label item as fruit.")

case _: Vegetable => println("label item as vegetable.")

case _ => println("unable to label the item. this seems to be an item for other department.")

}

Please note that the order of the case expressions matters. In the above case, if the additional case Fruit(name) expression is placed after case _: Fruit , the code will never ever reach it as it will match the case _: Fruit right away.
[]
['Programming', 'Software Engineering', 'Software Development', 'Data Science', 'Technology']