Is it possible to simplify this scala match statement using @ syntax?

Viewed 73

Is it possible to simplify the following match statement using @ syntax?

foo match {
  case f: Foo => y(f)
  case f if forceY => y(f)
  case _ => x
}

where forceY is a boolean.

I've tried the following but getting compile errors and it does look like possibly questionable syntax for the compiler to interpret. Perhaps this is impossible to express?

foo match {
  case f @(_: Foo | _ if forceY) => y(f)
  case _ => x
}
1 Answers
foo match {
  case f if f.isInstanceOf[Foo] || forceY => y(f)
  case _ => x
}

You cannot use @ specifically because the syntax f: Foo can only appear in the matching part of case, not in the condition (after if).

The original version isn't too bad, either. If what you actually have in the right hand side is longer than just y, you can define the y explicitly and leave the three cases as they are, as they read just fine.

Related