Joernsn Joernsn - 1 month ago 16
Scala Question

Yield only if pattern match

I am building a list of different case class objects based on a loop and a pattern match. I want to exclude (skip) the items hitting the default case (essentially filtering the list, and mapping to types in one step).

I'm probably too new to Scala to see all the possibilities. My attempt:

val events = for (ev <- data ) yield {

ev.sport match {
case "FOOTBALL" => new FootballEvent(ev)
case "SOCCER" => new SoccerEvent(ev)
case _ => None
}

}


I could filter the list afterwards, but I suspect there's some fancy Scala way of doing this :)

Please let me know if you have any idea of how this should best be done!

Answer

It is not that it is yield syntax, but you can use collect with pattern matching:

val events = data.collect { ev => ev.sport match {
     case "FOOTBALL" => new FootballEvent(ev) 
     case "SOCCER"   => new SoccerEvent(ev)
}}

Unlike better known .map and .foreach it wont fail on "other" case and instead just drop unmatched items.

Comments