14 Types Scala Pattern Matching – Syntax, Example, Case Class

In our previous Scala Tutorial, we studied Scala Trait Mixins and today we will see what is Scala Pattern Matching with examples. Moreover, we will discuss the types of pattern matching in Scala Programming Langauge. At last, we will discuss pattern matching with example & syntax and Scala Pattern Matching Case Class.

So, let’s start Scala Pattern Matching.

14 Types Scala Pattern Matching with Example - Latest 2018

14 Types Scala Pattern Matching with Example 

2. What is Scala Pattern Matching?

Scala lets us check a value against a pattern with pattern-matching. This is like a switch in Java. Not only we can use it to replace if-else ladders also we can use it to deconstruct a value into its constituent parts.

Scala pattern matching is made of constants, variables, constructors, and type tests. Using such a pattern, we can test if a value follows a pattern. We can only bind a variable name once in a pattern.

Stay updated with latest technology trends
Join DataFlair on Telegram!!

3. Examples of Scala Pattern Matching

Scala pattern may look something like this:

  • 1|2|3- This will match integers between 1 and 3.
  • Some(x)- This will match values of the format Some(v), where it binds x to the argument v for the constructor.
  • ex: IOException- This will match all instances of class IOException.
  • x::y::xs- This will match lists of length two or more. Here, it binds x to the first element in the list, y to the second, and xs to the remainder.
  • (x,_)- This will match pairs of values. x binds to the pair’s first component; the other is a wildcard.

Read about Scala Exceptions and Exception Handling

Let’s discuss the types of Scala Pattern Matching.

4. Types of Patterns Matching in Scala

Following are the different types of Scala Pattern Matching, let’s discuss them one by one:

Types of Patterns Matching in Scala

a. Variable Patterns

An identifier for a variable pattern begins with a lowercase letter. It matches a value and binds to it the variable name. The wildcard pattern ‘_’ is a special case of this.

SimplePattern ::= `_’
| varid

b. Typed Patterns

Typed patterns are of the format x:T, where x is a pattern variable and T is a type pattern. Here, x is of type T.

PatternOne ::= varid `:’ TypePat
| `_’ `:’ TypePat

c. Pattern Binders

Pattern binders look like x@p. Here, x is a pattern variable and p is the pattern.

PatternTwo ::= varid `@’ PatternThree

d. Literal Patterns

Literal patterns match the value that is equal to the literal we specify.

SimplePattern ::= Literal

e. Stable Identifier Patterns

Such a pattern is a stable identifier r. It will match value v that is equal to r.

SimplePattern ::= StableId

Let’s review Scala Iterator –  Cheat Sheet to Iterators in Scala 

f. Constructor Patterns

A constructor pattern takes the format c(p1,..,pn), with n>=0. Here, c is a stable identifier and p1,..,pn are element patterns. C is a constructor that denotes a case class.

SimplePattern ::= StableId `(‘ [Patterns] `)

g. Tuple Patterns

A tuple pattern is of the format (p1,..,pn). It is an alias for scala.Tuple n(p1,..pn), which is a constructor pattern with n>=2.

SimplePattern ::= `(‘ [Patterns] `)’

h. Extractor Patterns

An extractor pattern is of the format x(p1,..pn), where n>=0. While this is the form of a constructor pattern, x does not denote a case class. It denotes an object which allows pattern-matching through a member method unapply or unapplySeq.

SimplePattern ::= StableId `(‘ [Patterns] `)’

i. Pattern Sequences

Pattern sequences are of the format p1,..,pn. It may be as a constructor pattern or an extractor pattern. The constructor pattern is of the form c(q1,..,qm,p1,..pn) and the extractor pattern is of the form x(q1,..,qm,p1,..pn).

SimplePattern ::= StableId `(‘ [Patterns `,’] [varid `@’] `_’ `*’ `)’

Let’s discuss Scala File i/o: Open, Read and Write a File in Scala

j. Infix Operation Patterns

This is of the form p; op; q and is a shorthand for op(p,q) which is a constructor or extractor pattern.

Pattern3 ::= SimplePattern {id [nl] SimplePattern}

k. Pattern Alternatives

We can also specify a number of alternative patterns as p1|…|pn.

Pattern ::= Pattern1 { `|’ Pattern1 }

l. XML Patterns

For an XML pattern, the opening bracket ‘<’ for an element pattern should be able to start the lexical XML mode. It should be a single element pattern.

XmlPattern ::= ElementPattern

m. Regular Expression Patterns

Since version 2.0, these patterns have been discontinued in Scala.

n. Irrefutable Patterns

For a pattern p to be irrefutable for type T, one of the following conditions must be met:

  • It is a variable pattern
  • Typed pattern x:T’ and T<:T’
  • Constructor pattern c(p1,..,pn)

Let’s explore Scala Functions: Quick and Easy Tutorial

5. Type Patterns in Scala

These are made of types, type variables, and wildcards. For type patterns, we have the following forms:

  • A reference to one of these classes- C, p.C, or T#C. This will match any non-null instance of class.
  • Singleton type p. type. This will match the value denoted by path p.
  • A compound type pattern T1 with… with Tn. It will match all values matched by each type pattern.
  • A parameterized type pattern T[a1,…,an]. Here, ai can type variable patterns or wildcards. This will match all values matching T for arbitrary instantiations of type variables and wildcards.
  • Parameterized type pattern scala.Array[T1]. Here, T1 is a type pattern. This will match non-null instances of type scala.Array[U1]. Here, U1 matches T1.

6. A Syntax for Scala Pattern Matching

Here, we use the ‘match’ keyword and at least one ‘case’ clause. With the match keyword, we can apply a function to an object.

scala> import scala.util.Random
import scala.util.Random
scala> val x:Int=Random.nextInt(7)
x: Int = 5
scala> x match{
| case 1=>"One"
| case 2=>"Two"
| case _=>"One too many"
| }

res3: String = One too many

This gives us a random integer between 0 and 7. x is the left operand of the ‘match’ operator and the right operand is an expression with three cases/alternatives. In the end, we provide a “catch all” case for any value that doesn’t match any of the given case values. When a value matches the value of x, the value of the corresponding expression is evaluated.

Do you know about Scala Data Types with Examples 

7. Example of Pattern Matching in Scala

In the following example, it tests the integer x. If it is 1, it returns the string “One”; if it is 2, it returns “Two”. or If it is anything else, it returns “One too many”. You can say that this maps integers to strings.

scala> def test(x:Int):String=x match{
| case 1=>"One"
| case 2=>"Two"
| case _=>"One too many"
| }
test: (x: Int)String
scala> test(4)
res0: String = One too many
scala> test(1)
res1: String = One
scala> test(0)
res2: String = Many

8. Scala Pattern Matching Case Class

As we’ve previously discussed in our article on Case Classes, a case class is good for modeling immutable data. It has all vals; this makes it immutable. Let’s see how it helps with Scala pattern matching.

scala> case class Dog(breed:String,name:String,age:Int)
defined class Dog
scala> val leo=new Dog("Dogue de Bordeaux","Leo",2)
leo: Dog = Dog(Dogue de Bordeaux,Leo,2)
scala> val fluffy=new Dog("Lesser Indian Spitz","Fluffy",8)
fluffy: Dog = Dog(Lesser Indian Spitz,Fluffy,8)
scala> val candy=new Dog("Pug","Candy",6)
candy: Dog = Dog(Pug,Candy,6)
scala> for(dog<-List(leo,fluffy,candy)){
| dog match{
| case Dog("Dogue de Bordeaux","Leo",2)=>println("Hi, Leo")
| case Dog("Lesser Indian Spitz","Fluffy",8)=>println("Hi, Fluffy")
| case Dog(breed,name,age)=>println("Hi, "+name)
| }
| }

Output – Hi, Leo

Hi, Fluffy

Hi, Candy

For the case class, the compiler assumes the parameters to be vals. However, we can use the ‘var’ keyword to attain mutable fields. The compiler implements methods equals(), hashCode(), and toString() for the class. These use the fields as constructor arguments.

This means we do not need our own toString() methods.

9. Scala Pattern Guards

We can also add conditions to the code. Simply add an if statement after the case.

scala> val x=7
x: Int = 7
scala> x match{
| case 7 if x%2==0=>println("Odd")
| case 7 if x%2!=0=>print("Even")
| }


Do You How to Implement Scala Abstract Class with Examples

So, this was all about Scala Pattern Matching Tutorial. Hope you like our explanation.

10. Summary for Scala Pattern Matching

Hence, in this tutorial, we learned the introduction to Scala Pattern Matching with examples and syntax. In addition, we will discuss the types of Scala pattern matching. At last, we discussed pattern matching with example & syntax and Scala Pattern Matching Case Class. Furthermore, if you have any query regarding Scala Pattern Matching, feel free to ask in the comment section.

Related Topic- Scala Inheritance

For reference

1 Response

  1. Ansuman Satpathy says:

    The explanation on types of pattern matching appear rushed. Its better to avoid inclusion and addition of a reference to another resource than rushing with explanation.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.