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?
I think you just need to use it as a function, e.g.:
If you will define
pfasPartialFunction[String, Option[String]]you can also use other useful stuff likepf.isDefinedAt("x").If you will look in Scala Language Specification section 8.4 Pattern Matching Expressions, you will find following syntax:
So as you can see it’s impossible to use it as you described, but
pf("$")acts the same way.