Can define pattern match without match keyword

for example in akka we have:

def receive = {
    case "test" => log.info("received test")
    case _      => log.info("received unknown message")
  }

is it a pattern match or not? if it is not a pattern match what is it?

To me that looks like a Pattern Matching Anonymous Function.

1 Like

This is called a PartialFunction if you look at the type definition of Receive it is a PartialFunction[Any, Unit], it’s partial because not matching all possible cases won’t result in a match exception. You can also use this notation for a normal function.

For example:


val f : Int => Option[Int] = {
   case 3 => Some(3)
   case _ => None
}

The above works without the match keyword because they are functions. However if you have a concrete value you need to use the match keyword to tell the compiler what you want to pattern match on.

2 Likes

That’s right: SLS§8.5: Pattern Matching | Scala 2.13

Two quick notes, just to be explicit:

  1. that’s only true if the expected type is a PartialFunction (which it is for Akka’s receive :sweat_smile:);
  2. it’s only true if you don’t use apply, but one of PartialFunction’s methods, like applyOrElse.

Also, as of Scala 2.13.1, when the expected type is PartialFunction you can drop the case when specifying a total function. So

def receive = (x => println(x))
// or
def receive = println(_)

instead of

def receive = { case x => println(x) }
3 Likes