rmsam rmsam - 3 months ago 12
Scala Question

Scala pattern matching with tuple: matching equal values in the tuple

I have created a function to retrieve a given value from the Pascal Triangle and I've used

if
statements. Now I want to refactor the function to use pattern matching.

My
if
based function looks like this:

def valueAt(row: Int, column: Int): Int = {
// ...
else if (row == column) 1 // last column
//
}


My second version of this function, using pattern matching has the following signature:

def valueAt2(row: Int, column: Int): Int = (row, column) match {
// ...
}


Is it possible to define a
case
for when the
row
and
column
have the same value?

I have tried using the same variable name in the
case
, like this:

case (x, x) => 1 // last column


And I have also tried to use the value of the
row
in the column, like this:

case (_, row) => 1 // last column


But they don't work. In the first case I have a compilation error and in the second the IDE says that I'm shadowing the variable
row
from the
match
.

It this possible?

Thanks.

Ven Ven
Answer

For the first one, use an if guard:

(1, 2) match { case (x, y) if x == y => 1; ... }

For the second one, when you want to match a variable (instead of binding and shadowing it), you can use backticks (`):

(1, 2) match { case (_, `row`) => 1; ... }
Comments