6

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?

Péter Török
  • 114,404
  • 31
  • 268
  • 329
  • 2
    It's an early initializer, as explained in "Scala for Impatient, p 122, or Sclaa in Depth, p. 71 – Gene T Feb 23 '13 at 05:10

1 Answers1

3

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.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
  • Also, with structural types the `extends` keyword is not used, is it? At least not in the examples I found in PiS2. – Péter Török Feb 22 '13 at 23:22
  • @PéterTörök You can extend a structural type, but a trait or class can extend a structural type, for whatever that is worth. – Daniel C. Sobral Feb 23 '13 at 00:15
  • For reference, [here is your own answer](http://stackoverflow.com/questions/4712468/in-scala-what-is-an-early-initializer#4716273) regarding early initializers. – 0__ Feb 23 '13 at 16:12