Scala:你可以使用“foo match { bar }”吗?在没有括号的表达式中?
这里为什么需要括号?我应该知道一些优先规则吗?
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
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如 Agilesteel 所说,匹配不被视为简单的表达式,if 语句也不被视为简单的表达式,因此您需要用括号将表达式括起来。来自 Scala 语言
规范,6 表达式,p73,匹配是一个 Expr,就像一个 if 一样。 + 运算符两侧仅接受 SimpleExpr。
要将 Expr 转换为 SimpleExpr,必须用 () 将其括起来。
为了完整性而复制:
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:
经过对 Scala 规范的一些检查后,我想我可以尝试一下。
如果我错了请纠正我。
首先,
if
或match
被定义为Expr
- 表达式。您正在尝试创建一个中缀表达式(通过在两个表达式之间使用运算符来定义)
但是 规范(第 3.2.8 节)指出:
它还指出:
所以我的看法是 Scala 不知道首先要减少什么:匹配或方法“+”调用。
看看这个答案
如果我是的话请纠正我错误的。
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.
匹配表达式不被视为简单表达式。这是一个类似的例子:
显然你不能在任何你想要的地方编写复杂的表达式。我不知道为什么,希望对此主题有更多了解的人能给您更好的答案。
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.