【问题标题】:Switch case in closure form not matching properly闭包形式的开关盒不正确匹配
【发布时间】:2015-04-12 03:35:50
【问题描述】:

我正在尝试使用 Groovy 的模式匹配基于部分字符串创建一个 switch case。我已经完成了这项工作 -

String s = "abc";

switch(s){
  case { it =~ /b/ } :
    //this works
    break;
 .....
}

但是当我尝试抽象出闭包时,我遇到了问题 -

String s = "abc";
def partialMatch = {string, pattern -> string =~ /$pattern/}

switch(s){
  case partialMatch(s, "b"):
    //this doesn't work
    break;
 .....
}

看起来匹配有效,但由于某种原因,该案例仍未触发。这是为什么呢?

【问题讨论】:

    标签: regex string groovy switch-statement closures


    【解决方案1】:

    您需要将partialMatch 放入一个闭包中,以便switch 执行它:

    case {partialMatch(s, "b")}:
    

    【讨论】:

      猜你喜欢
      • 2015-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      • 2012-02-14
      相关资源
      最近更新 更多