Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala class extends {}

Tags:

types

scala

By chance I came across weird compiling Scala syntax:

class Some extends {
  def hi = println("hi")
}

Guys:

  • Is it an official Scala supported syntax?
  • Does it mean simply extending the Object?
  • Does it somehow relate to "duck typing"?
  • Do you know interesting or tricky usages of this?

Thanks.

like image 315
Max Avatar asked Jul 19 '14 05:07

Max


People also ask

What does Extends do in Scala?

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.

Can a class extend a trait Scala?

Classes and objects can extend traits, but traits cannot be instantiated and therefore have no parameters.

Can a Scala class extend a Java class?

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.

Can we extend multiple classes in Scala?

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.).


1 Answers

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")
}
like image 93
wingedsubmariner Avatar answered Sep 30 '22 14:09

wingedsubmariner