What is the purpose of extending an anonymous type in Scala?
I'm trying to get a better understanding of Scala,开发者_如何学JAVA 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!
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.
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).
It's called Early definitions and they deal with super class initialization order problem.
精彩评论