3.1 Class Hierarchies
Object-oriented languages (including Scala) implement dynamic method dispatch.
This means that the code invoked by a method call depends on the runtime type of the object that contains the method.
3.2 How Classes Are Organized
Classesand Objects are organized in packages.
To place a class or object inside a package, use a package clause at the top of your source file.
package progfun.example object Hello { ... }
This would place Hello in the package progfun.examples. You can then refer to Hello by its fully qualified name progfun.examples.Hello. For instance, to run the Hello program.
Nothing is at the bottom of Scala's type hierarchy. It is a subtype of every other type.
There is no value of type Nothing.
Why is that useful?
- To signal abnormal termination
- As an element type of empty collections
Every reference class type alss has null as a value.
The type of null is Null.
Null is a subtype of every class that inherits from Objects; it is incompatible with subtypes of AnyVal.
3.3 Polymorphism
Type parameterization means that classes as well as methods can now have types as parameters.
Type parameters do not affect evaluation in Scala.
We can assume that all type parameters and type arguments are removed before evaluating the program.
This is also called type erasure.
Language that use type erasure include Java, Scala, Haskell, Ml, OCaml.
Some other languages keep the type parameters around at run time, these include C++, C#, F#.
Polymorghism means that a function type comes "in many forms".
In programming it means that:
- the function can be applied to arguments of many types, or
- tye type can have instances of many types.
We have seen two principal forms of polymorphism:
- subtyping: instances of a subclass can be passed to a base class
- generics: instances of a function or class are created by type parameterization.
-
trait List[T] { def isEmpty: Boolean def head: T def tail: List[T] def nth(n: Int): T } class Cons[T](val head:T, val tail: List[T]) extends List[T] { def isEmpty = false def nth(n: Int) = { if(n < 0) throw new IndexOutOfBoundsException("index less than 0") else if(n == 0) head else tail nth(n-1) } } class Nil[T] extends List[T] { def isEmpty = true def head: Nothing = throw new NoSuchElementException("Nil.head") def tail: Nothing = throw new NoSuchElementException("Nil.tail") def nth(n: Int) = throw new IndexOutOfBoundsException("Nil") }