By chance I came across weird compiling Scala syntax:
class Some extends {
def hi = println("hi")
}
Guys:
Object
?Thanks.
extends: The extends keyword in Scala is used to inherit features of one class by another class. baseClass extends parentClass. This extends keyword is used to inherit class while creating a new one. With: the with keyword in Scala is used when we need to inherit more than one class by another class.
Classes and objects can extend traits, but traits cannot be instantiated and therefore have no parameters.
You can extend a base Scala class and you can design an inherited class in the same way you do it in Java (use extends key word), but there are two restrictions: method overriding requires the override keyword, and only the primary constructor can pass parameters to the base constructor.
You can't extend multiple classes, but you can extend several traits. Unlike Java interfaces, traits can also include implementation (method definitions, data members, etc.).
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
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.
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With