Home > Enterprise >  scala pattern matching to drop some cases
scala pattern matching to drop some cases

Time:12-17

With Scala 2.12, I am looping an array with pattern matching to create a new array as below.

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")

If an element matches one of the two patterns, a new element is added into the new array arrNew. Those that do not match will be dropped. My codes actually loop arrText twice with filter. If I do not include case x =>"0", there will be errors complaining some elements are not getting matched. Are the codes below the only way of looping just once? Any way I can loop only once with case matching?

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

CodePudding user response:

you can use 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)
}
  • Related