Chapter 4, Exercise 21
As I wrote an hour and a half ago,
the Scala compiler bug that I ran into with the cleaner-looking
variant on the 2D array made me decide to skip Exercise 20,
the 3D array version of the same thing.
Added later: On the first of each month that I'm
doing this, I'll put handy links to the inspirations.
Chapter 4, Exercise 21
Exercise 21 asks us to
Comment the line marked (1) in
ExplicitStatic.java and verify that the static initialization
clause is not called. Now uncomment one of the lines marked (2)
and verify that the static initialization clause is called.
Now uncomment the other line marked (2) and verify that static
initialization only occurs once.
Well, first we need to translate ExplicitStatic.java into
a reasonable Scala facsimile. For ease of reference, I've
colored the three relevant lines
red (1),
orange (first (2)),
and
violet (second (2)).
// Explicit static initialization ...
class Cup {
def this (marker: Int) = {
this();
Console.println("Cup(" + marker + ")");
}
def f (marker: Int) = Console.println("f(" + marker + ")");
}
class Cups_dyn {
Console.println("new Cups_dyn()");
}
object Cups_static {
var c1 : Cup = _;
var c2 : Cup = _;
c1 = new Cup(1);
c2 = new Cup(2);
}
object c4x21 {
def main (args: Array[String] ) = {
Console.println("Inside main()");
Cups_static.c1.f(99); // (1)
}
var x = new Cups_dyn; // first (2)
var y = new Cups_dyn; // second (2)
}
Comparing the Java results with the Scala results:
(I) As printed in the book: of the colored statements, only
the red one ((1)) is enabled: Scala and Java print the same
set of messages:
Inside main()
Cup(1)
Cup(2)
f(99)
(II) As directed, we commented out the red (1), and uncommented (enabled) the orange statement (the first (2)).
Scala:
new Cups_dyn()
Inside main()
Java:
Cup(1)
Cup(2)
Cups()
Inside main()
The difference here is that the static initialization in class Cups
does get called in Java, but not in Scala. This is because the Scala
version has separated the Cups class into a static part (an object
named Cups_static) and a dynamic part (the class Cups_dyn). And we
no longer reference the Cups_static object in this Scala translation.
(III) Next, enable the violet statement (the second (2)).
We see a similar difference between the Scala and the Java:
Scala Orange and Violet:
new Cups_dyn()
new Cups_dyn()
Inside main()
Java Orange and Violet:
Cup(1)
Cup(2)
Cups()
Cups()
Inside main()
(IV) Finally (for extra credit), we enable all three of the
colored statements. We get the same sets of (analogous)
messages, but they come out in a different order.
Scala does a sort of lazy initialization of the static
bits, while java does a more eager initialization of them.
Scala All three uncommented:
new Cups_dyn()
new Cups_dyn()
Inside main()
Cup(1)
Cup(2)
f(99)
Java All three:
Cup(1)
Cup(2)
Cups()
Cups()
Inside main()
f(99)
1:45:05 AM