Chapter 4, Exercises 15-16
A couple more initialization exercises.
Chapter 4, Exercise 15
15. Create a class containing an uninitialized String reference.
Demonstrate that this reference is initialized by Java to null.
As we've seen, Scala has no such thing as an uninitialized
String -- you're required to make it explicitly initialized
to something, even if that something is just the "default
value" for that type.
class c4x15c { var s : String = _; };
object c4x15 {
def main ( args: Array[String] ) =
Console.println( "Is it null? " + (new c4x15c).s );
}
Chapter 4, Exercise 16
16. Create a class with a String field that is initialized at
the point of definition, and another one that is initialized
by the constructor. What is the difference between the two
approaches?
Each c4x16c instance starts out with the same value for sdefn,
versus each c4x16c instance starting out with some
value (that you passed to the constructor) for scons.
Other distinctions to note beside this one: val versus var
(like C++'s "const" or not), and a member of an object
(like C++ or Java's static members) versus a member of
a class.
class c4x16c {
var sdflt : String = _;
var sdefn : String = "c4x16c sdefn";
var scons : String = _;
def this ( ts: String ) = { this(); scons = ts; }
};
object c4x16 {
def main ( args: Array[String] ) = {
val v1 = new c4x16c ;
Console.println( "v1.sdflt " + v1.sdflt );
Console.println( "v1.sdefn " + v1.sdefn );
Console.println( "v1.scons " + v1.scons );
val v2 = new c4x16c( "v2 ctor arg" );
Console.println( "v2.sdflt " + v2.sdflt );
Console.println( "v2.sdefn " + v2.sdefn );
Console.println( "v2.scons " + v2.scons );
val v3 = new c4x16c( "v3 ctor arg" ); ;
Console.println( "v3.sdflt " + v3.sdflt );
Console.println( "v3.sdefn " + v3.sdefn );
Console.println( "v3.scons " + v3.scons );
}
}
10:52:30 PM