[英]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
[用例] 通過將部分 function 應用於此序列中定義了 function 的所有元素來構建新集合。
val arrNew=arrText.collect {
case x if x.startsWith("A") =>x.substring(12, 20)
case x if x.startsWith("B") =>x.substring(21, 40)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.