4

I feel like this is a silly question, but I'll ask anyway... I'm trying to do something like this:

def func(x: Int, y: Int) = { val value: Int = 0 //from config (x, y) match { case (value, value) => "foo" case _ => "bar" } } 

But both the repl and intelliJ shower me with warnings. (e.g. "patterns after a variable pattern cannot match"; "suspicious shadowing by a variable pattern"; etc.). Is there a correct way to match on non-literal values?

3
  • Does this answer your question? Why does pattern matching in Scala not work with variables? Commented Oct 3, 2023 at 10:36
  • @Clément Man I wrote this 10 years ago i have no idea. Commented Oct 4, 2023 at 12:36
  • yeah, this weird comment phrasing is the auto-comment that SO posts when you flag a duplicate. Sorry for the noise. Commented Oct 5, 2023 at 23:59

1 Answer 1

14

Yes! There are two ways to get what you want. The first is to capitalize the names of the variables you wish to match against:

def func(x: Int, y: Int) = { val Value: Int = 0 // from config (x, y) match { case (Value, Value) => "foo" case _ => "bar" } } 

If you don't want to go that route (because it's not idiomatic to capitalize variable names, etc.), you can backtick them in the match:

def func(x: Int, y: Int) = { val value: Int = 0 // from config (x, y) match { case (`value`, `value`) => "foo" case _ => "bar" } } 

I'd suggest using backticks in most situations.

Sign up to request clarification or add additional context in comments.

3 Comments

it might be worth adding that the reason is that pattern matching requires a stable identifier pattern, which you can obtain using literals, backticks or capitalized names.
I love it when Travis Brown goes downscale. Is this the only TB answer without a type param or a macro in it?
@som-snytt: I like to kick back on Sundays.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.