Chapter 6, Exercise 13
13. Create a class with a method that is overloaded three times.
Inherit a new class, add a new overloading of the method, and
show that all four methods are available in the derived class.
Well, fact is, they're not. Scala's overloading is more like
C++ in this respect (won't overload across scopes) than like
Java seems to be.
package x;
class over {
def loaded : Int = 42;
// def loaded () : Int = 43;
def loaded (i:Int) : Int = i*2;
}
class under extends over {
def loaded (s:String) : Int = s.length();
}
object c6x13 {
def main ( args: Array[String] ) = {
val toaded = new under;
val truck = new over;
val i = toaded loaded("Under");
val j = truck loaded( i );
// val k = truck loaded( );
val k = 1010101;
val l = truck loaded;
W.rn( "Got " + i + j + k + l );
}
}
Interesting: If I uncomment the loaded that takes an empty parameter
list (i.e., the one that returns 43), I get:
c6x13.scala:9: overlapping overloaded alternatives;
the two following alternatives of method loaded have
the same erasure: ()int
alternative 1: def loaded: scala.Int
alternative 2: def loaded(): scala.Int
def loaded () : Int = 43;
And if I try to get the 42 or the i*2 methods from the
derived class, I get
c6x13.scala:23: type mismatch;
found : scala.Int
required: java.lang.String
val j = truck loaded( i );
^
one error found
12:26:49 AM