Scala 类扩展了 {} [英] Scala class extends {}
问题描述
偶然我遇到了奇怪的 Scala 语法编译:
By chance I came across weird compiling Scala syntax:
class Some extends {
def hi = println("hi")
}
各位:
- 它是 Scala 支持的官方语法吗?
- 这是否意味着简单地扩展
Object
? - 它是否与鸭子打字"有关?
- 你知道这个有趣或棘手的用法吗?
谢谢.
推荐答案
这实际上是 Scala 语法中的一个奇怪的怪癖.在开始类的主体之前,允许使用无关的 extends
.以下是 Scala 语法摘要<的相关部分/a>:
This is actually a strange quirk in Scala's syntax. An extraneous extends
is allowed before beginning the body of the class. Here are the relevant parts from the Scala Syntax Summary:
ClassDef ::= id [TypeParamClause] {ConstrAnnotation} [AccessModifier]
ClassParamClauses ClassTemplateOpt
ClassTemplateOpt ::= ‘extends’ ClassTemplate | [[‘extends’] TemplateBody]
ClassTemplate ::= [EarlyDefs] ClassParents [TemplateBody]
ClassTemplateOpt
是类参数之后的所有内容,在本例中,从 extends
开始的所有内容.extends
的通常用法是 ClassTemplateOpt
的第一个交替,extends
后跟父或早期初始化程序.但是,早期初始化程序不能包含 def
,并且无法将大括号的内容解释为父级.它不能是结构类型,因为 hi
有一个具体的定义.
ClassTemplateOpt
is everything after the class's parameters, in this case everything from extends
onwards. The usual use of extends
is the first alternation of ClassTemplateOpt
, with extends
being followed either by a parent or an early initializer. However, an early initializer cannot contain a def
, and there is no way to interpret the contents of the braces as a parent. It cannot be a structural type because hi
has a concrete definition.
第二个选项允许类参数紧跟在类主体之后,无需使用extends
.但是,允许使用可选的 extends
.OP 代码中的 extends
就是一个例子,它完全等同于没有可选扩展的相同代码:
The second alternation allows the class parameters to be immediately followed by the class body, without using extends
. However, an optional extends
is allowed. The extends
in OP's code is an example of this, and is exactly equivalent to the same code without the optional extends:
class Some {
def hi = println("hi")
}
这篇关于Scala 类扩展了 {}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!