Pattern matching with conjunctions (PatternA AND PatternB)

前端 未结 2 1721
难免孤独
难免孤独 2020-12-07 07:25

Scala has a language feature to support disjunctions in pattern matching (\'Pattern Alternatives\'):

x match {
    case _: String | _: Int => 
    case _          


        
相关标签:
2条回答
  • 2020-12-07 08:23

    A possible problem with this is the bloated translation that the pattern matcher generates. Here is the translation of the sample program, generated with scalac -print. Even -optimise fails to simplify the if (true) "_" else throw new MatchError() expressions.

    Large pattern matches already generate more bytecode than is legal for a single method, and use of this combinator may amplify that problem.

    If && was built into the language, perhaps the translation could be smarter. Alternatively, small improvements to -optimise could help.

    0 讨论(0)
  • 2020-12-07 08:26

    I really like this trick. I do not know of any existing way to do this, and I don't foresee any problem with it -- which doesn't mean much, though. I can't think of any way to create a Not.

    As for adding it to the standard library... perhaps. But I think it's a bit hard. On the other hand, how about talking Scalaz people into including it? It looks much more like their own bailiwick.

    0 讨论(0)
提交回复
热议问题