Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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??) => ...
like image 915
johnsam Avatar asked Sep 11 '16 13:09

johnsam


1 Answers

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
like image 120
Yuval Itzchakov Avatar answered Oct 13 '22 11:10

Yuval Itzchakov