super 不在操作员位置?
在 Scala 中,当方法调用位于操作符位置时,调用方法是有语法糖的。例如(5).+(3)
可以写成5 + 3
。其规则是
class X {
def x(i: Int) = i * 2
}
class Y extends X {
override def x(i: Int) = super.x(i + 1)
}
当我将点留在 super 后面时,我会收到编译器错误。在这里,super
是对象,x
是方法,i + 1
是参数,因此我不明白为什么会出现错误。谁能解释一下吗?
in Scala there is syntactic sugar by calling a method when the method call is in operator position. For example (5).+(3)
can be written as 5 + 3
. The rule for this is <object>.<method>(<parameter>)
. It this rule is true the dot and the parentheses can be left. But I found an exception of this rule: it is not able to write the super-keyword in operator position:
class X {
def x(i: Int) = i * 2
}
class Y extends X {
override def x(i: Int) = super.x(i + 1)
}
When I leave the dot behind the super I get a compiler error. Here, super
is the object, x
the method and i + 1
the parameter therefore I don't understand why I get an error. Can anyone explain it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信这是因为
super
关键字必须(但请参阅 huynhjl 的评论和下面的详细信息)后跟一个.
,然后跟一个有效的成员标识符 -- < em>这似乎是语法产生规则。考虑到
val expr = (super)
没有任何有用的含义,并且应该始终是无效的(在这方面,它与this
完全不同,后者本身就是一个有效的表达式)。在语法级别要求super.member
形式可能是有意为之,但这需要一些挖掘。根据规范的措辞(请参阅 huynhjl 的评论)和 per语法“摘要”规则。快乐编码。
更新(参考资料):
来自 Scala 语言规范 2.8 讨论
第 6.5 节中的 super
:摘自 Scala 语法摘要(A 章):
I believe it is because the
super
keyword must (but see the comment by huynhjl and details below) be followed with a.
and then followed with a valid member identifier -- it seems to be grammar production rule.Consider that
val expr = (super)
has no useful meaning and should always be invalid (in this regard it is quite different fromthis
which is a valid expression by itself). Requiring thesuper.member
form at the grammar level islikely intentional, but it would require some digging.intentional per the wording the specification (see the comment by huynhjl) and per the grammar "summary" rules.Happy coding.
Update (references):
From the Scala Language Specification 2.8 discussing
super
in Section 6.5:And from the Scala Syntax Summary (Chapter A):