Scala:你可以在没有括号的表达式中使用“foo match {bar}”吗?
发布时间:2020-12-16 19:02:35 所属栏目:安全 来源:网络整理
导读:为什么需要括号?我应该知道一些优先规则吗? scala 'x' match { case _ = 1 } + 1console:1: error: ';' expected but identifier found. 'x' match { case _ = 1 } + 1 ^scala ('x' match { case _ = 1 }) + 1res2: Int = 2 谢谢! 解决方法 正如Agilestee
为什么需要括号?我应该知道一些优先规则吗?
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 谢谢! 解决方法
正如Agilesteel所说,一个匹配不被认为是一个简单的表达式,也不是一个if语句,所以你需要用括号来包围表达式.从
The Scala Language
Speci?cation,6表达式,p73,匹配是一个Expr,就像一个if.只有SimpleExpr被接受在运算符的任一侧. 要将Expr转换成SimpleExpr,你必须用()来包围它. 复制完整性: 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} | ‘:’ ‘_’ ‘*’ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |