Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "extends {..}" clause in Scala object definition, without superclass name, do?

I found this code example in Programming in Scala, 2nd Ed. (Chapter 25, Listing 25.11):

object PrefixMap extends {
  def empty[T] = ...

  def apply[T](kvs: (String, T)*): PrefixMap[T] = ...

  ...
}

Why is the extends clause there without a superclass name? It looks like extending an anonymous class, but for what purpose? The accompanying text doesn't explain or even mention this construct anywhere. The code actually compiles and apparently works perfectly with or without it.

OTOH I found the exact same code on several web pages, including this (which looks like the original version of the chapter in the book). I doubt that a typo could have passed below the radars of so many readers up to now... so am I missing something?

I tried to google it, but struggled even to find proper search terms for it. So could someone explain whether this construct has a name and/or practical use in Scala?

like image 522
Péter Török Avatar asked Feb 22 '13 22:02

Péter Török


People also ask

Can an object extend another object in Scala?

Limitations of Scala ObjectYou cannot extend an object to create a class or another object. Objects cannot have a public constructor. And that makes sense as well. Because they are singleton objects and you don't want to use them as a blueprint to instantiate new objects.

What is extend 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.

What is the difference between extends and with in Scala?

The first thing you inherit from can either be a trait or a class, using the extends keyword. You can define further inherited traits (and only traits) using the with keyword.

Can an object extend a trait?

Traits are used to share interfaces and fields between classes. They are similar to Java 8's interfaces. Classes and objects can extend traits, but traits cannot be instantiated and therefore have no parameters.


1 Answers

Looks like a print error to me. It will work all the same, though, which probably helped hide it all this time.

Anyway, that object is extending a structural type, though it could also be an early initialization, if you had with XXX at the end. MMmmm. It looks more like an early initialization without any class or trait to be initialized later, actually... structure types do not contain code, I think.

like image 79
Daniel C. Sobral Avatar answered Oct 13 '22 23:10

Daniel C. Sobral