rmsam - 1 year ago 76

Scala Question

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

`if`

My

`if`

`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`

`row`

`column`

I have tried using the same variable name in the

`case`

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

And I have also tried to use the value of the

`row`

`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`

`match`

It this possible?

Thanks.

Answer Source

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; ... }
```