How does | (pipe) in pattern matching work?

前端 未结 2 1359
再見小時候
再見小時候 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 10:01

    Yes the pipe (|) is a built-in for pattern matching (see the scala language reference). The Pattern matching section (section 8) defines in section 8.1.11 what is called Pattern Alternatives. The definition says:

    A pattern alternative p1 | ... | pn consists of a number of alternative patterns pi . All alternative patterns are type checked with the expected type of the pattern. They may no bind variables other than wildcards. The alternative pattern matches a value v if at least one its alternatives matches v.

    So yes, the pipe is a built-in that is context sensitive to pattern matching.

提交回复
热议问题