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.:
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.
精彩评论