Interfaces, subtypes and matching
(1/5)Interfaces, Basis and Details
Interfaces Basis
Interfaces in 42 are quite similar to interfaces in other OO languages. There are however a couple of important differences.
While implementing an interface method, you can avoid the
type signature.
For example, in the following code, to implement
Interface diamonds are allowed; that is, the following code is correct:
You can refine the return type of an interface method, by repeating the full type signature with the desired return type. On the other hand, the parameter types cannot be refined.
(2/5) Interfaces and class methods
Interface methods in 42 are all abstract; that is, without bodies.
A version of the body will be provided by all classes implementing the interface.
This also includes class methods.
For example, consider the following code:
In 42 interfaces do not have
implemented class methods.
Sometimes we want to semantically associate some behaviour with an interface.
For example we could check intersections between shapes using
the draw method.
What we would need, is a traditional (non dynamically dispatched) static method.
In 42, static methods are just nested classes with a single class method with the empty name. In 42 adding new classes is very common, so do not be scared of adding a new class just to host a method.
For example
(3/5)Subtyping
Dynamic dispatch is the most important feature of object oriented languages.
Subtyping is the main feature supporting dynamic dispatch; for example
we can iterate over a list of
Interfaces and classes represent two fundamentally alternative compromises between the providers and users of objects:
- Interfaces allows client code to be implicitly parametric on the behaviour of individual objects. The client code can make no assumption on the specific implementation of the interface.
- Classes allow client code to rely on their invariants. The user code is forced to pass only a specific kind of implementation.
In simpler terms, if we have a
If instead we have a
(4/5)Matching
It is possible to inspect the runtime type of an object by using matching. We will now provide various examples of matching and explain the behaviour.
We can use an
The syntax
The code below:
is equivalent to: That is: we can match out the result of any no-arg method into a variable with the same name, plus an optional numeric suffix. This syntax can also be used inside of the(5/5)Interfaces, subtypes and matching, summary
Interfaces in 42 serve the same role that they serve in other languages,
with a little bit of a twist in the details.
The big news is that decorators (
In the right conditions, matching is a useful tool to reduce code size and complexity.
However, dynamic dispatch is still the preferred option in the general case. On the other hand type matching works only on a finite
number of hard-coded cases, making it fragile with respect to code evolution.