# 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.

def multiply(i:Int):Int = i match {
case 4 => i * 3
case _ => i * 2
}
//Prints 12
println(multiply(4))

//Prints 4
println(multiply(2))

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.

def multiply(i:Int):Int = i match {
case 4|6 => i * 3
case _ => i * 2
}
//Prints 12
println(multiply(4))

//Prints 18
println(multiply(6))

//Prints 6
println(multiply(3))

In the above example, we have a function called multiply, which takes a parameter and returns a value. If the value is 4 or 6 it will multiply the value by 3. Underscore _ acts as a catch-all for any other values and it will multiply by 2.

match-case can also be used to check the type. Which is a much cleaner way for type checking instead of an exception handler. See Below

def greetings(x: Any):String = x match {
case x:String =&gt; "Hello " + x
case _ =&gt; "Oops - I don't what it is"
}
//Prints - Hello Sam
println(greetings("Sam"))

//Prints - Oops - I don't what it is
println(greetings(2))

In the above example, the code checks the input type of the parameter. There is no need of calling the instanceOf method.

Now let’s mix things up a bit. What if we want to multiply all numbers greater than or equal to 5 by 2 and less than 5 by 3. If anything else is passed let’s just return a message. Let’s add a bit more to match case – if statement. It is also called the guard clauseSee Below

def multiply(i:Any):Any = i match {
case i:Int if x>=5 => i * 2
case i:Int if x i * 3
case 0: 0
case _ => "Oops!"
}
//Prints 12
println(multiply(4))

//Prints 12
println(multiply(6))

//Prints 0
println(multiply(0))

//Prints Oops!
println(multiply("Hello World!"))

In the next entry let’s focus on applying pattern matching to collections.