MomStopFlashing
MomStopFlashing

Reputation: 265

scala: convert match statement to pattern matching anonymous function - with values

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?

Upvotes: 21

Views: 16289

Answers (1)

Marth
Marth

Reputation: 24812

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 cases 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).

Upvotes: 30

Related Questions