Multiple extracts in scala

I often find that I want to combine several elements / extractors into one line, but this does not seem to be allowed. eg:.

text match { case regex1(a) | regex2(a) => a + "-" } 

(although a is the same type for both sockets)

so I am forced to reorganize like this (which can become ugly if there are several of them, all are handled by different matches mixed with inline answers)

 text match { case regex1(a) => op(a) case regex2(a) => op(a) } def op(a: String) = a + "-" 

Is there a cleaner way? And will it be supported in Scala in the future?

+4
source share
1 answer

No , this is not possible in the general case. However, there are several workarounds that can be used to combine pattern matching cases:

  • Match the super class of cases you want to group.
  • Use the case a @ _ if boolexpr(a) or boolexpr(a) =>
  • Sort common code into functions, as it was in your example

And maybe others. I don’t think this will change soon, as it will help to write critical magicians / cases.

+3
source

Source: https://habr.com/ru/post/1500186/


All Articles