johnsam johnsam - 2 months ago 10
Scala Question

How to pattern match even number in the case in scala?

I have the following code:

def myfunct(n: Int, steps: Int) = n match {
case 1 => steps
case (x) => if (x % 2 == 0) ...


Is there anyway to move the even number matching logic into the case ? Do I need a case class?

Such as:

def myfunct(n: Int, steps: Int) = n match {
case 1 => steps
case (even number??) => ...

Answer

Yes, it's called a guard:

def myfunct (n: Int, steps: Int) = n match {
  case 1 => steps
  case even if n % 2 == 0 => // stuff
  case odd => // other stuff