Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala, what is an "early initializer"?

Tags:

scala

In Martin Odersky's recent post about levels of programmer ability in Scala, in the Expert library designer section, he includes the term "early initializers".

These are not mentioned in Programming in Scala. What are they?

like image 362
oxbow_lakes Avatar asked Jan 17 '11 11:01

oxbow_lakes


2 Answers

Early initializers are part of the constructor of a subclass that is intended to run before its superclass. For example:

abstract class X {     val name: String     val size = name.size }  class Y extends {     val name = "class Y" } with X 

If the code was 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).

like image 146
Daniel C. Sobral Avatar answered Oct 09 '22 10:10

Daniel C. Sobral


As far as I can tell, the motivation (as given in the link above) is:

"Naturally when a val is overridden, it is not initialized more than once. So though x2 in the above example is seemingly defined at every point, this is not the case: an overridden val will appear to be null during the construction of superclasses, as will an abstract val."

I don't see why this is natural at all. It is completely possible that the r.h.s. of an assignment might have a side effect. Note that such code structure is completely impossible in either C++ or Java (and I will guess Smalltalk, although I can't speak for that language). In fact you have to make such dual assignments implicit...ticilpmi...EXplicit in those languages via constructors. In the light of the r.h.s. side effect uncertainty, it really doesn't seem like much of a motivation at all: the ability to sidestep superclass side effects (thereby voiding superclass invariants) via ASSIGNMENT? Ick!

Are there other "killer" motivations for allowing such unsafe code structure? Object-oriented languages have done without such a mechanism for about 40 years (30-odd years, if you count from the creation of the language), why include it now?

It...just...seems...dangerous.

like image 27
Mark Gerolimatos Avatar answered Oct 09 '22 11:10

Mark Gerolimatos