【问题标题】:Scala pattern match default guardsScala 模式匹配默认守卫
【发布时间】:2012-08-17 13:56:32
【问题描述】:

我想做很多 case 语句,每个语句前面都有相同的警卫。我可以用不需要重复代码的方式来做吗?

"something" match {
   case "a" if(variable) => println("a")
   case "b" if(variable) => println("b")
   // ...
 }

【问题讨论】:

  • 你能把代码分成分支吗?所以拉出“if variable”并在里面进行匹配,对于你拥有的任何其他分支都一样吗?

标签: scala pattern-matching


【解决方案1】:

你可以创建一个提取器:

class If {
  def unapply(s: Any) = if (variable) Some(s) else None
}
object If extends If
"something" match {
  case If("a") => println("a")
  case If("b") => println("b")
  // ...
}

【讨论】:

    【解决方案2】:

    似乎 OR(管道)运算符的优先级高于守卫,因此以下工作:

    def test(s: String, v: Boolean) = s match {
       case "a" | "b" if v => true
       case _ => false
    }
    
    assert(!test("a", false))
    assert( test("a", true ))
    assert(!test("b", false))
    assert( test("b", true ))
    

    【讨论】:

      【解决方案3】:

      0__ 的回答很好。或者,您可以先匹配“变量”:

      variable match {
        case true => s match {
          case "a" | "b" | "c" => true
          case _ => false
        }
        case _ => false
      }
      

      【讨论】:

        猜你喜欢
        • 2019-03-01
        • 2017-06-23
        • 2015-08-15
        • 2011-09-28
        • 1970-01-01
        • 1970-01-01
        • 2011-01-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多