scala - 如何(管道)在模式匹配工作中?

标签 scala pattern-matching

你可以写:

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/

相关文章:

Erlang,特定 map 键上的模式匹配?

python - Python中列表的模式匹配

scala - 不将正则表达式匹配应用到案例类中

scala - 如何将 shell 脚本(bash)转换为 Scala 代码?

performance - SCALA:在使用“.contains()”或“.exists()”的情况下,哪种数据结构是最佳的?

java - 捕获字符串上匹配字符(单个或重复)之间的所有字符

haskell - 如何有效地组合 haskell 模式匹配

sql - 获取 '/' 字符后的字符串

arrays - 在Scala中如何对数组中的连续元素进行分组

scala - 在 scala 中将值从一个参与者传递到另一个参与者