Scala – Pattern Matching & Collections

Pattern matching is not just limited to simple types it can also be applied to collections as well. Let’s see how it can be applied to Lists. See Below

def checkingList(l:List[Int]):String = l match {
  case List(10,_,_) => "List Starts with 10"
  case Nil => "No Elements in the list"
  case _ => "Oops!"
}

//Prints - List Starts with 10
println(checkingList(List(10,1,2)))

//Prints - No Elements in the list
println(checkingList(List()))

//Prints - Oops
println(checkingList(List(10,1,2,20)))

In the above example, we want to check if the list of 3 elements starts with 10 or not. This logic works fine when the list has just 3 elements. But fails if the list has more than 3 elements. The last print shows the failure condition.

 Extending the logic so that lists of any size can be checked. See Below.

def checkingList(l:List[Int]):String = l match {
  case List(10,_*) => "List Starts with 10"
  case Nil => "No Elements in the list"
  case _ => "Oops!"
}

//Prints - List Starts with 10
println(checkingList(List(10,1,2)))

//Prints - No Elements in the list
println(checkingList(List()))

//Prints - List Starts with 10
println(checkingList(List(10,1,2,20)))

//Prints - Oops
println(checkingList(List(1,1,2,20)))

In the above code, the only change we made was in the second line of the function and introduced _* – is a special instance of type ascription which tells the compiler to treat a single argument of a sequence type as a variable argument sequence. It is not as complicated as it sounds essentially it means you can pass multiple arguments.

Let’s mix it up a bit. What if you want to check the second element in the list is 10. See Below

def checkingList(l:List[Int]):String = l match {
  case List(_,10,_*) => "Second element in the List is 10"
  case Nil => "No Elements in the list"
  case _ => "Oops!"
}

//Prints - Second element in the List is 10
println(checkingList(List(1,10,2,1)))

//Prints - Oops
println(checkingList(List(1,1,2,20)))

The examples which we have discussed above can also be applied to Sequences, Vectors, and other collections. Keep in mind all these can also be achieved by calling collection operators/methods. This is an alternate approach.

By now you have realised how powerful match case is and it is a massive step-up from the traditional case-switch.

Next entry we look at pattern matching with case classes.

Leave a Comment