Class Hierarchy
Class Hierarchy
Consider the task of writing a class for sets of integers with the following
operations.
end NonEmpty
Terminology
The definitions of contains and incl in the classes Empty and NonEmpty
implement the abstract functions in the base trait IntSet.
It is also possible to redefine an existing, non-abstract definition in a
subclass by using override.
Example
In the IntSet example, one could argue that there is really only a single
empty IntSet.
So it seems overkill to have the user create many instances of it.
We can express this case better with an object definition:
An object and a class can have the same name. This is possible since
Scala has two global namespaces: one for types and one for values.
Classes live in the type namespace, whereas objects live in the term
namespace.
If a class and object with the same name are given in the same sourcefile,
we call them companions. Example:
class IntSet ...
object IntSet:
def singleton(x: Int) = NonEmpty(x, Empty, Empty)
This defines a method to build sets with one element, which can be called
as IntSet.singleton(elem).
A companion object of a class plays a role similar to static class definitions
in Java (which are absent in Scala).
Programs
So far we have executed all Scala code from the REPL or the worksheet.
But it is also possible to create standalone applications in Scala.
Each such application contains an object with a main method.
For instance, here is the “Hello World!” program in Scala.
object Hello:
def main(args: Array[String]): Unit = println(”hello world!”)
Once this program is compiled, you can start it from the command line
with
Once this function is compiled, you can start it from the command line
with
Write a method union for forming the union of two sets. You should
implement the following abstract class.