Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching on non-literal values

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?

like image 797
Lasf Avatar asked Dec 09 '22 06:12

Lasf


1 Answers

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.

like image 160
Travis Brown Avatar answered Dec 28 '22 22:12

Travis Brown