Scala 模式匹配以删除某些案例

scala pattern matching to drop some cases

使用 Scala 2.12,我正在使用模式匹配循环数组以创建一个新数组,如下所示。

val arrNew=arrText.map {
  case x if x.startsWith("A") =>x.substring(12, 20)
  case x if x.startsWith("B") =>x.substring(21, 40)
  case x => "0"
}.filter(_!="0")

如果一个元素与两种模式中的一种相匹配,则将一个新元素添加到新数组中arrNew。那些不匹配的将被丢弃。我的代码实际上使用过滤器循环 arrText 两次。如果我不包含 case x =>"0",将会出现错误,抱怨某些元素没有得到匹配。下面的代码是循环一次的唯一方法吗?我只能用 case 匹配循环一次吗?

map { x =>
      if (condition1) (output1)
      else if (condition2) (output2)
    }

你可以使用collect

[use case] Builds a new collection by applying a partial function to all elements of this sequence on which the function is defined.


val arrNew=arrText.collect {
  case x if x.startsWith("A") =>x.substring(12, 20)
  case x if x.startsWith("B") =>x.substring(21, 40)
}