Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 520
Daniel Hanke Avatar asked Mar 29 '15 18:03

Daniel Hanke


1 Answers

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

like image 161
Marth Avatar answered Oct 21 '22 10:10

Marth