like similar question: Convert match statement to partial function when foreach is used. Now similarly, IntelliJ asks me to improve my code. The difference is, that I use values for the matching:
val matchMe = "Foo"
keys.foreach(key =>
key match {
case `matchMe` => somethingSpecial()
case _ => somethingNormal(key, calcWith(key))
})
Refactoring this to a anonymous pattern-matching function would look something like:
keys.foreach {
case `matchMe` => somethingSpecial(_)
case _ => somethingNormal(_, calcWith(_)) //this doesn't work
}
Note that in the second case, I cannot use _
since I need it twice. Is there some way to use an anonymous pattern-matching function here?
You can't use the wildcard _
here, its purpose is to indicate you don't care about the value you're matching against.
You can use a named parameter :
keys.foreach {
case `matchMe` => somethingSpecial(matchMe)
case nonSpecialKey => somethingNormal(nonSpecialKey, calcWith(nonSpecialKey))
}
Without any restrictions placed on it, it will match any value. Do note that the order of case
s is important, as case x => ...
match anything and will essentially shortcut other case
statements.
As an aside, I don't think your somethingSpecial(_)
does what you want/expect it to. It's only a short version of x => somethingSpecial(x)
, not somethingSpecial(matchMe)
.
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