Home > Back-end >  Scala patternmatching
Scala patternmatching

Time:11-03

I have following code for pattern matching in Scala:

response.flatMap(employee =>
            employee match {
              case e if e.type == Manager => e.headoffice
              case e if e.type == Clerk => e.branch
              case _ => None
            }
          )

Is this optimum way of doing pattern matching? Can it be made more concise?

CodePudding user response:

You can try matching on type:

response.flatMap(e => e.type match {
    case Manager => e.headoffice
    case Clerk => e.branch
    case _ => None
})

CodePudding user response:

I personally would do it like this:

response.map(e => e -> e.`type`).flatMap {
  case (e, Manager) => e.headoffice
  case (e, Clerk) => e.branch
  case _ => None
}
  • Related