Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala pattern matching option string

Tags:

scala

I have an option of string called failureType. According to values of this String I have to decide what type of object I want to create. Something like -

val failure: Option[FailureType] = failureType map (f => f.toLowerCase match {
          case "build" => FailureType.BuildFailure
          case "test" => FailureType.TestFailure
          case "service timeout" => FailureType.ServiceTimeout
          case "job timeout" => FailureType.JobTimeout
          case "work item timeout" => FailureType.WorkItemTimeout
        } )

My problem is I get Match Error if I give values other than "build", "test", "service timeout", "job timeout" or "work item timeout" to failureType. Which makes sense because I am not doing any default catching. So my problem is how to do this default catching ? If I do

case _ => None

At the end of other case statements, I would get error, because of course I am inside Map. My other option seem to be not using map at all and directly doing match -

val failure: Option[FailureType] = failureType match {
          case Some("build") => FailureType.BuildFailure
          case Some("test") => FailureType.TestFailure
          case Some("service timeout") => FailureType.ServiceTimeout
          case Some("job timeout") => FailureType.JobTimeout
          case Some("work item timeout") => FailureType.WorkItemTimeout
          case _ => None
        }

But in this case I lose the ability to do case insensitive matching.

like image 801
ocwirk Avatar asked Jul 19 '26 10:07

ocwirk


1 Answers

What you are looking for is .collect:

val failure = failureType.map(_.toLowerCase).collect { 
   case "build" => FailureType.BuildFailure
   case "test" => FailureType.TestFailure
   case "service timeout" => FailureType.ServiceTimeout
   case "job timeout" => FailureType.JobTimeout
   case "work item timeout" => FailureType.WorkItemTimeout
}

.collect takes a PartialFunction, and will return the result of its application if the function is defined on the argument or None otherwise.

like image 75
Dima Avatar answered Jul 21 '26 00:07

Dima



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!