How does | (pipe) in pattern matching work?

前端 未结 2 1363
再見小時候
再見小時候 2020-12-16 09:28

You can write:

str match { case \"foo\" | \"bar\" => ... }

At first glance it looks like | could be an extractor object, ho

2条回答
  •  忘掉有多难
    2020-12-16 09:59

    | is not implemented in the library, it is interpreted by the Scala compiler. It builds a new pattern that is defined as the disjunction between two subpatterns that don't bind any variable (although the newly formed pattern can itself be bound; i.e., you can write stuff like

    try { /*...*/ }
    catch {
      case e @ (_: IOException | _: IllegalArgumentException) => /*...*/
    }
    

    and e gets as type the most specific supertype of the listed alternatives).

提交回复
热议问题