【问题标题】:scala pattern matching to drop some casesscala 模式匹配以删除某些情况
【发布时间】:2022-01-19 12:03:34
【问题描述】:

使用 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)
    }

【问题讨论】:

标签: scala pattern-matching


【解决方案1】:

你可以使用collect

[用例]通过将偏函数应用于定义函数的序列的所有元素来构建新集合。


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

【讨论】:

    猜你喜欢
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 2017-10-05
    • 1970-01-01
    相关资源
    最近更新 更多