scalacollectionspattern-matching

Avoiding redundant else


class Person( id:String , age:Option[Double])

val rows: Seq[Person] = List(Person("a",None),Person("c",None),Person("e",50))

val ages = rows.foreach( r => r.age match{
case Some(s) => "prefix" + s.toString
case _ => 0 // redundant pollute
})

How can I avoid the records with age as None during iteration - rather than filtering later.


Solution

  • Usually, map and filter can be expressed as a single operation with collect, as in the following example:

    rows.collect {
      case Person(_, Some(age)) => s"prefix$age"
    }
    

    You can play around with this code here on Scastie.