11

I'm trying to get a better understanding of Scala, and I can't seem to find a valid usecase for code like the following:

class C extends { def m() { /* ... */ } }

What is the rationale for allowing such constructs?

Thanks!

Eyvind
  • 5,221
  • 5
  • 40
  • 59

3 Answers3

12

I guess the only rationale here is "avoid special cases if possible". You can extend any class, an anonymous class is a class, so you can extend an anonymous class.

Kim Stebel
  • 41,826
  • 12
  • 125
  • 142
  • You are probably right (+1). Would love an actual use case, though, if one does indeed exist :) – Eyvind Sep 28 '11 at 08:15
  • I agree with Kim, inheriting allows to share behaviors or to represent a given hierarchy. But If the parent class in anonymous, you cannot have two child classes extending the same parent class. – paradigmatic Sep 28 '11 at 13:03
  • 1
    You can't extend `final` classes. I suppose anonymous classes could be made final, but in the absence of any reason to extend an anonymous class it probably doesn't make any difference whether they're final or not. – Luigi Plinge Sep 28 '11 at 13:59
  • I'd like to remind users that this answer is wrong. It has been the accepted answer for a few years now and it's misleading since it has nothing to do with avoiding special cases. See my answer below. – leinaD_natipaC Jul 11 '15 at 22:31
11

That is not, in fact, an anonymous class! It's an early initializer and it runs as part of the constructor that goes before its superclass. Quoting the excellent answer from another stackoverflow question:

abstract class X {
    val name: String
    val size = name.size
}

class Y extends {
    val name = "class Y"
} with X

If the code were written instead as

class Z extends X {
    val name = "class Z"
}

then a null pointer exception would occur when Z got initialized, because size is initialized before name in the normal ordering of initialization (superclass before class).

Community
  • 1
  • 1
leinaD_natipaC
  • 4,299
  • 5
  • 21
  • 40
1

It's called Early definitions and they deal with super class initialization order problem.

lisak
  • 21,611
  • 40
  • 152
  • 243