How to match an even number in a 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) ...

In any case, do you need to move the logic with an even number to the register? Do I need a case class?

For instance:

def myfunct(n: Int, steps: Int) = n match {
  case 1 =>  steps
  case (even number??) => ...
+4
source share
4 answers

Yes, he is 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
+6
source

You can also use extractors:

object Even {
  def unapply(x: Int) = if (x % 2 == 0) Some(x) else None
}

object Odd {
  def unapply(x: Int) = if (x % 2 == 1) Some(x) else None
}

List(1,2,3,4).foreach { 
  case Even(x) => println(s"$x: even")
  case Odd(x) => println(s"$x: odd")
}
+6
source

Patten Matching

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

Even Odd

object One {
  def unapply(n: Int) = if (n == 1) Some(1) else None
}

object Even {
 def unapply(n: Int) = if (n % 2 == 0) Some(n) else None
}

def myfunct (n: Int, steps: Int) = n match {
 case One(x) =>  steps
 case Even(x) => doSomething
 case x => doSomething
}
+3

n mod, tupled,

def f(n: Int, steps: Int) = (n, n % 2) match {
  case (1, _) => steps
  case (_, 0) => steps + 2
  case _      => steps + 1
}
+2

Source: https://habr.com/ru/post/1654272/


All Articles