开发者

super not in operator position?

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: In开发者_开发技巧t) = 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?


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 from this which is a valid expression by itself). Requiring the super.member form at the grammar level is likely intentional, but it would require some digging. intentional per the wording the specification (see the comment by huynhjl) and per the grammar "summary" rules.

class X {
  def x(): X = this
}
class Y extends X {
  // Still kaboom of course -- message is effectively the same
  // and indicates a grammar production has been violated.
  // Message: error: '.' expected but '}' found.
  override def x(): X = super
}

Happy coding.


Update (references):

From the Scala Language Specification 2.8 discussing super in Section 6.5:

A reference super.m refers statically to a method or type m in the least proper supertype of the innermost template containing the reference. It evaluates to the member in the actual supertype of that template which is equal to m or which overrides m. The statically referenced member m must be a type or a method ... The super prefix may be followed by a trait qualifier [T], as in C.super[T].x. This is called a static super reference. In this case, the reference is to the type or method of x in the parent trait of C whose simple name is T.

And from the Scala Syntax Summary (Chapter A):

stableId ::= id
           | Path ‘.’ id
           | [id ’.’] ‘super’ [ClassQualifier] ‘.’ id
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜