Let’s take the factorial algorithm as an example.

def factorial(x: BigInt): BigInt = { if (x == 0) 1 else x * factorial(x - 1) }

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

def factorial(x: BigInt): BigInt = x match { case 0 => 1 case _ => x * factorial(x - 1) }

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.

def factorial(x: BigInt): BigInt = x match { case y: BigInt if y == 0 => 1 case _ => x * factorial(x - 1) }

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