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!
A match expression is not considered as simple expression. Here is a similar example:
Apparently you can't write complex expressions wherever you want. I don't know why and hope that someone with more knowledge of the topic will give you a better answer.
After some inspection in the Scala specification, I think I can give it a shot. If I am wrong please correct me.
first, an
if
ormatch
are defined asExpr
- expressions.You are trying to create an infix expression (defined by the use of the operator between two expressions)
However the especification (section 3.2.8) states that :
It also also states that:
So my take is that Scala does not know what to reduce first: the match or the method '+' invocation.
Take a look at this answer
Please correct me if I am wrong.
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: