你可以写:
str match { case "foo" | "bar" => ... }
乍一看,
|
可能是提取器对象,但是:str match { case |("foo", "bar") => ... }
不起作用。 (而且我也看不到如何实现。)
所以这是一个神奇的内置运算符?
(我相信我以前曾在SO上看到过这个问题,但无法搜索...)
最佳答案
是的,管道(|
)是模式匹配的内置工具(请参阅the scala language reference)。模式匹配部分(第8节)在第8.1.11节中定义了所谓的模式替代项。定义说:
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.
因此,是的,管道是内置的,对模式匹配上下文敏感。
关于scala - 如何(管道)在模式匹配工作中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6484137/