Let’s take the factorial algorithm as an example.

[scala]

def factorial(x: BigInt): BigInt = {

if (x == 0) 1 else x * factorial(x – 1)

}

[/scala]

One might expect to convert this into a pattern matched equivalent as follows.

[scala]

def factorial(x: BigInt): BigInt = x match {

case 0 => 1

case _ => x * factorial(x – 1)

}

[/scala]

In fact this will give you the error below.

type mismatch; found : Int(0) required: BigInt Factorial.scala

The reason is that BigInt is not a case class and does not have an unapply() method in its companion object.

However a small modification allows the pattern matching implementation to succeed.

[scala]

def factorial(x: BigInt): BigInt = x match {

case y: BigInt if y == 0 => 1

case _ => x * factorial(x – 1)

}

[/scala]

Arguably the if/else equivalent is simpler but if you always use pattern matching you’ll want this version.