smeeb smeeb - 1 month ago 12
Scala Question

Scala match statements with inline regexes

I am trying (if at all possible) to get a Scala match/case statement to perform an inline regex match for me.

Specifically, I have a method that will run a

match
, and if the input to the method starts with the string "fizz", then I would like the match statement to select the correct case:

def animalToSound(animal : String) : String = {
animal match {
case "duck" => "quack"
case "lion" => "roar"
case "dog" => "woof"
case matchesFizzRegex(animal) => "heyo!"
case _ => "meow"
}
}

def matchesFizzRegex(animal : String) : ??? = {
val fizzRegex = "fizz*".r
if(fizzRegex.match(animal)) {
???
} else {
???
}
}


So if I call
animalToSound("fizzBuzz")
, then the desired behavior is:


  1. Does "fizzBuzz" equal "duck"? No. So try the next case.

  2. Does "fizzBuzz" equal "lion"? No. So try the next case.

  3. Does "fizzBuzz" equal "dog"? No. So try the next case.

  4. Does "fizzBuzz" match the fizz regex (any string starting with 'fizz')? Yes, so return "heyo!"



Any ideas how I can get this working properly?

Answer

Simple and straight forward

Use pattern matching guards and matches method of string

def animalToSound(animal : String) : String = animal match {
        case "duck"   =>    "quack"
        case "lion"   =>    "roar"
        case "dog"    =>    "woof"
        case x if x matches "fizz.*" =>  "heyo!"
        case _        =>    "meow"
    }
Comments