Search code examples
scalapattern-matchingpartialfunction

How can I use PartialFunctions to compose my match statements?


Consider the following:

scala> object Currency extends Enumeration {
     |   type Currency = Value
     |   val USD = Value
     |   val GBP = Value
     |   val EUR = Value
     |   val TRY = Value // Turkish lira
     |   val NGN = Value // Nigerian naira
     | }
defined module Currency

scala> import Currency._
import Currency._

scala> val pf: (String) => Option[Currency] = {
     |     case "$" => Some(USD)
     |     case "€" => Some(EUR)
     |     case "£" => Some(GBP)
     |     case "₦" => Some(NGN)
     |     case _ => None
     |   }
pf: (String) => Option[Currency.Currency] = <function1>

I thought I'd be able to then do this:

scala> "$" match pf
<console>:1: error: '{' expected but identifier found.
       "$" match pf
                 ^

But no. Am I missing something basic here? My hope was that my PartialFunction could be used and reused in match statements. Is this not possible?


Solution

  • I think you just need to use it as a function, e.g.:

    pf("$")
    

    If you will define pf as PartialFunction[String, Option[String]] you can also use other useful stuff like pf.isDefinedAt("x").


    If you will look in Scala Language Specification section 8.4 Pattern Matching Expressions, you will find following syntax:

    Expr ::= PostfixExpr ‘match’ ‘{’ CaseClauses ‘}’
    CaseClauses ::= CaseClause {CaseClause}
    CaseClause ::= ‘case’ Pattern [Guard] ‘=>’ Block
    

    So as you can see it's impossible to use it as you described, but pf("$") acts the same way.