Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Can you use "foo match { bar }" in an expression without parentheses?

Why are the parentheses needed here? Are there some precedence rules I should know?

scala> 'x' match { case _ => 1 } + 1
<console>:1: error: ';' expected but identifier found.
       'x' match { case _ => 1 } + 1
                                 ^

scala> ('x' match { case _ => 1 }) + 1
res2: Int = 2

Thanks!

like image 943
Guillaume Martres Avatar asked Sep 23 '11 13:09

Guillaume Martres


1 Answers

As Agilesteel says, a match is not considered as a simple expression, nor is an if statement, so you need to surround the expression with parentheses. From The Scala Language Specification, 6 Expressions, p73, the match is an Expr, as is an if. Only SimpleExpr are accepted either side of the + operator.

To convert an Expr into a SimpleExpr, you have to surround it with ().

Copied for completeness:

Expr ::= (Bindings | id | ‘_’) ‘=>’ Expr
    | Expr1
Expr1 ::= ‘if’ ‘(’ Expr ‘)’ {nl} Expr [[semi] else Expr]
    | ‘while’ ‘(’ Expr ‘)’ {nl} Expr
    | ‘try’ ‘{’ Block ‘}’ [‘catch’ ‘{’ CaseClauses ‘}’] [‘finally’ Expr]
    | ‘do’ Expr [semi] ‘while’ ‘(’ Expr ’)’
    | ‘for’ (‘(’ Enumerators ‘)’ | ‘{’ Enumerators ‘}’) {nl} [‘yield’] Expr
    | ‘throw’ Expr
    | ‘return’ [Expr]
    | [SimpleExpr ‘.’] id ‘=’ Expr
    | SimpleExpr1 ArgumentExprs ‘=’ Expr
    | PostfixExpr
    | PostfixExpr Ascription
    | PostfixExpr ‘match’ ‘{’ CaseClauses ‘}’
PostfixExpr ::= InfixExpr [id [nl]]
InfixExpr ::= PrefixExpr
    | InfixExpr id [nl] InfixExpr
PrefixExpr ::= [‘-’ | ‘+’ | ‘~’ | ‘!’] SimpleExpr
SimpleExpr ::= ‘new’ (ClassTemplate | TemplateBody)
    | BlockExpr
    | SimpleExpr1 [‘_’]
SimpleExpr1 ::= Literal
    | Path
    | ‘_’
    | ‘(’ [Exprs] ‘)’
    | SimpleExpr ‘.’ id s
    | SimpleExpr TypeArgs
    | SimpleExpr1 ArgumentExprs
    | XmlExpr
Exprs ::= Expr {‘,’ Expr}
BlockExpr ::= ‘{’ CaseClauses ‘}’
    | ‘{’ Block ‘}’
Block ::= {BlockStat semi} [ResultExpr]
ResultExpr ::= Expr1
    | (Bindings | ([‘implicit’] id | ‘_’) ‘:’ CompoundType) ‘=>’ Block
Ascription ::= ‘:’ InfixType
    | ‘:’ Annotation {Annotation}
    | ‘:’ ‘_’ ‘*’
like image 138
Matthew Farwell Avatar answered Sep 22 '22 21:09

Matthew Farwell