Scala – Pattern Matching & Case Classes

Pattern matching is also applied to case classes. Rather patter matching is always discussed along with case classes. Let’s see how we can apply pattern matching to case classes. Let’s look at an example. See Below In the above example, there is a Person case class defined and a match-case pattern matching function is defined which checks the lastName element of the Person class. If the lastName is Doe it prints that it has “Found a Doe!” and if it lastName is Cole it prints it has “Found a Cole!!”, otherwise, it prints “Unknown Last Name”. Let’s start to mix up – In one of the first blog entry of Pattern matching we had discussed Or clause in values. We can use it in case classes as well. See Below The result is whenever the lastName is Cole or Doe it will print “Found a Doe or Cole!”. Now let’s apply … Read more

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 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. 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 … Read more

Scala – Pattern Matching – Values, Types & Variables

Pattern matching in Scala is one of the most widely used and discussed topics. In simple terms, it is similar to the switch-case. Let’s use that familiarity to get a simple understanding of pattern matching and build up from there. Let’s first look at a simple match-case expression and see how it works. In the above example, we have a function called multiply, which takes a parameter and returns a value. If the value is 4 it will multiply the value by 3. Underscore _ acts as a catch-all for any other values and it will multiply by 2. This is simple. But what if we want to apply the same logic for more than one patterns. Writing individual case statements would make the code unnecessarily long. Let’s apply an OR logic to the expression. In the above example, we have a function called multiply, which takes a parameter and returns … Read more