Match cases on Scala
Functional programming is a well-know paradigm present in languages like Scheme, Haskell, Lisp and others, the main goal is to provide code easy to write and reuse.
This paradigm concept came from mathematics, where expressions are evaluated to functions and they always return the same result every time asked. Think about the Haskell code below:
If you try to put some output from this pure function, the code will miserably fail. Functional languages don’t like to deal with side-effects, for this reason they are immutable and selfish to share state. Scala came with purpose of bringing mixed-paradigm concept to JVM, taking the benefits from both the worlds: functional and object oriented.
This language was designed to keep your hand safe from write a bunch of code, with the gift of full concurrency support. One of the great features inherited from functional languages is pattern matching. This feature provides a way to choose between multiple choices based on types. In Java, case conditions are restricted to primitive or enumerated types, is not possible to have switch/case accordingly with object type. Scala addresses these gaps more efficiently than Java:
There’s nothing new for Ruby programmers, that also have pattern matching inside. The code above created an immutable variable with val and match keyword which provides a way to apply pattern matching function. Functional features built inside Scala enhanced matching case work more efficiently than languages like Java or Ruby. Take a look at this example matching on sequences:
Matching on sequences enable you to look inside collections in a eager evaluation. Here we are looking for a List that have 3 like a second item and 7 for the last, the bizarre _ is a wildcard, it matches anything not defined in cases. Match cases are not only for collections, you can use this function to find objects. Suppose you specifically need to know if an object contains some value, match on classes could solve this problem, better than deal with a lot of frameworks. The last one of our Swiss knife:
Pattern Matching become useful when you have to deal with Actors (subject for another default), because case classes are sent as messages and have to be parsed when received. This feature is not a particularity from Scala, is a inheritance from functional languages and help you where object oriented languages don’t fit well.