scala - 具有多个匹配项的模式匹配

标签 scala pattern-matching

考虑以下 Scala 代码。

val a = "both"

a match {
    case "both" | "foo" => println ("foo")   // case 1
    case "both" | "bar" => println ("bar")   // case 2
}

我要 match工作,以便如果 a == "both" , Scala 将执行这两种情况。这是可能的还是有其他选择来实现我想要的?

最佳答案

标准模式匹配将始终只匹配一种情况。您可以通过使用模式可以被视为部分函数这一事实(请参阅 Language Specification ,第 8.5 节,模式匹配匿名函数)并定义您自己的匹配运算符来接近您想要的结果:

class MatchAll[S](scrutinee : =>S) {
  def matchAll[R](patterns : PartialFunction[S,R]*) : Seq[R] = {
    val evald : S = scrutinee
    patterns.flatMap(_.lift(evald))
  }
}

implicit def anyToMatchAll[S](scrut : =>S) : MatchAll[S] = new MatchAll[S](scrut)

def testAll(x : Int) : Seq[String] = x matchAll (
  { case 2 => "two" },
  { case x if x % 2 == 0 => "even" },
  { case x if x % 2 == 1 => "neither" }
)

println(testAll(42).mkString(",")) // prints 'even'
println(testAll(2).mkString(","))  // prints 'two,even'
println(testAll(1).mkString(","))  // prints 'neither'

语法略有不同,但对我来说,这样的结构仍然是 Scala 强大功能的见证。

你的例子现在写成:
// prints both 'foo' and 'bar'
"both" matchAll (
  { case "both" | "foo" => println("foo") },
  { case "both" | "bar" => println("bar") }
)

( 编辑 huynhjl 指出他给出了与 this question 惊人相似的答案。)

关于scala - 具有多个匹配项的模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7565599/

相关文章:

c++ - C++ 中的 "Pimp my Library"

function - Scala 函数文字中的 `return`

java - 除了 Scala 之外,在 JVM 上运行的替代多线程优化语言?

iterator - 如何在 vec 上映射并在 Rust 中使用带有模式匹配的闭包

c# - 单元测试简单的树结构操作

f# - 完整模式匹配的编译时约束

java - mysql 在 playframework 的子句中查询

scala - 通过 Shapeless 获取默认案例类参数

android - 我可以制作图案密码屏幕锁定安卓应用吗

algorithm - F# 中模式匹配在幕后是如何工作的?