6

我正在对冒号分隔的字符串进行一些模式匹配,如下所示:

case s:String => s.split(":") match {
  case Array("foo","bar") => ...
  case Array("hello",_,_) => ...
  ...
}

如何重新排列代码以将名称分配给返回的数组s.split(":")

我尝试了以下方法无济于事:

case s:String => val x = s.split(":") match {
  case Array("foo","bar") => // try to use x here
  ...
}
4

1 回答 1

12
case s:String => s.split(":") match {
  case x @ Array("foo","bar") => ...
  case x @ Array("hello",_,_) => ...
  ...
}

或者

case s:String =>
  val x = s.split(":")
  x match {
    case Array("foo","bar") => ...
    case Array("hello",_,_) => ...
    case Array(aStr, "bar") => println(aStr.toUpperCase)
    ...
}
于 2012-07-18T12:10:08.833 回答