Search code examples
scalapattern-matchingpartialfunction

What is the reference of the object that a partial function matches on?


Looking at this function as an example:

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

What object is being matched on? On the right hand side of the arrows, how can I refer to the object being matched on?


Solution

  • You can do it with an if-guard:

    def receive: String => Unit = {
      case str if str == "test" => println(str)
      case _ => println("other")
    }
    
    Option("test").map(receive) // prints "test"
    Option("foo").map(receive) // prints "other"
    

    Note that if you have an object that you want to refer to, then stuff like e.g. foo: Foo(s) won't work (foo: Foo will, but then you lose the reference to Foo's value s). In that case you need to use the @ operator:

    case class Foo(s: String)
    
    def receive: Foo => Unit = {
      case foo@Foo(s) => println(foo.s) // could've referred to just "s" too
      case _ => println("other")
    }
    
    Option(Foo("test")).map(receive) // prints "test"