Reputation: 4572
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??) => ...
Upvotes: 6
Views: 5188
Reputation: 20415
Pattern match on n
and its mod
, tupled,
def f(n: Int, steps: Int) = (n, n % 2) match {
case (1, _) => steps
case (_, 0) => steps + 2
case _ => steps + 1
}
Upvotes: 4
Reputation: 14825
Using Patten Matching guards
def myfunct (n: Int, steps: Int) = n match {
case 1 => steps
case x if x % 2 == 0 => doSomething
case x => doSomething
}
Other way is to define Even
and Odd
extractors
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
}
Upvotes: 3
Reputation: 9225
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")
}
Upvotes: 6
Reputation: 149578
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
Upvotes: 10