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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With