Chapter 4, Exercises 1-2, Thinking in Scala
Chapter 4, Exercise 1
I wonder how one declares ... or even whether one can declare ...
and implement a no-argument constructor to do some action
(like, say, printing a log message)
upon the creating of a c4x1c, without having to do it in
an overloaded constructor.
For this exercise, I added some extra println's.
class c4x1c {
def this ( i:Int ) = {
this();
Console.println( " ... creating a c4x1c, with argument " + i );
}
}
object c4x1 {
def main ( args: Array[String] ) = {
Console.println( "Declaring a c4x1c 'o' ..." );
val o = new c4x1c;
Console.println( "Declaring a c4x1c 'p' (1) ..." );
val p = new c4x1c(1);
Console.println( "Declaring a c4x1c 'q' (2) ..." );
val q = new c4x1c(2);
Console.println( "All done." );
}
}
Chapter 4, Exercise 2
Overloaded constructors are a little weird in Scala.
The name is always "this", and the the parser won't
accept the definition unless the first thing it does is
a call to another constructor. The no-argument
constructor is, I gather, the basic one that the
compiler generates. I guess that answers the wonder
in the first half of this posting.
class c4x2c {
def this ( i:Int ) = {
this();
Console.println( " ... creating a c4x2c, with int argument " + i );
}
def this ( s:String ) = {
this();
Console.println( " ... creating a c4x2c, with String argument '"
+ s + "'." );
}
}
object c4x2 {
def main ( args: Array[String] ) = {
Console.println( "Declaring a c4x2c 'o' ..." );
val o = new c4x2c;
Console.println( "Declaring a c4x2c 'p' (1) ..." );
val p = new c4x2c(1);
Console.println( "Declaring a c4x2c 'q' (2) ..." );
val q = new c4x2c(2);
Console.println( "Declaring a c4x2c 'r' (Last One) ..." );
val r = new c4x2c( "Last One" );
Console.println( "All done." );
}
}
PS, I talked a bit with Bruce Eckel tonight at the
Python BayPIGgies meeting, and told him about
this Scala effort here on GIGO, and about
THECLAPP
series in Java and Lisp, as well as
Bill Clementson's catalog of the CLAPP one.
I put a brief review of the Python meeting on my
zia weblog.
1:24:31 AM