scala模式匹配以删除某些情况



使用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中。不匹配的将被删除。我的代码实际上用filter循环arrText两次。如果我不包括case x =>"0",就会有错误抱怨某些元素不匹配。下面的代码是循环一次的唯一方法吗?在case匹配的情况下,我可以只循环一次吗?

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

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

相关内容

最新更新