scala 关键字优先级
scala 中如何定义“关键字优先级”?
考虑这段代码:
for(i <- 1 to 10) yield i
这没关系,我得到一个从 1 到 10 的 Seq
,但是当我尝试立即匹配时:
for(i <- 1 to 10) yield i match {case x => x.head}
出现编译错误:error: value head is not Int 的成员。
我可以将 for ... yield
括在括号中以赋予其优先级:
{for(i <- 1 to 10) yield i} match {case x => x.head}
但我仍然想知道第二个示例代码是如何解释的。我希望第二个示例也能正常工作,而无需用括号括起来。
任何人都可以向我解释它或指出我在规范中的正确章节吗?
how is "keyword precedence" defined in scala?
Consider this piece of code:
for(i <- 1 to 10) yield i
This is OK, I get a Seq
from 1 to 10, but when i try to match right after:
for(i <- 1 to 10) yield i match {case x => x.head}
There is a compile error: error: value head is not a member of Int
.
I can surround for ... yield
in parentheses to give it precedence:
{for(i <- 1 to 10) yield i} match {case x => x.head}
But I'm still wondering how is the second example code interpreted. I would expect the second example to work properly as well, without surrounding it with parens.
Can anyone explain it to me or point me to the right chapter in specification?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第二个示例解释为:
for 的近似语法如下:
Since
i match { case x => x.head }
解析为有效的表达式(令牌明智),这就是编译器将如何看待它。因此,如果 Expr 看起来像一个表达式,那么它就会被处理。根据这个推理,以下语句是有效的:并且它们都等同于
注意:Scala 语言规范可用 这里(第一个链接)。相关部分位于 A 章(Scala 语法摘要)的第 161 页。
The second example is interpreted as:
The approximate syntax for for is like:
Since
i match { case x => x.head }
parses as a valid expression (token wise), that's how the compiler will see it. So if Expr looks like an expression, that's how it will be treated. By that reasoning, the following statements are valid:and they are all equivalent to
Note: the Scala Language Specification is available here (first link). The relevant section is on page 161 in the Chapter A (Scala Syntax Summary).