How do I match multiple arguments?

Phil H picture Phil H · Mar 22, 2011 · Viewed 24.1k times · Source

I have a function:

def func(a: int, b: int, c: double): int

And I want to match various possible scenarios

  1. Wherever c is 0, return b-a
  2. Wherever c > 9, return 0
  3. Wherever a=b return 0

And so on, before doing some more complex logic if none of the above are satisfied.

Do I have to match c separately first, or can I match on a,b,c, like _,_,0?

Answer

tenshi picture tenshi · Mar 22, 2011

You can pattern match all described cases like this:

def func(a: Int, b: Int, c: Double) = (a, b, c) match {
    case (a, b, 0) => b - a
    case (a, b, c) if c > 9 || a == b => 0
    case _ => 1 // add your logic here
}