More on interface delegations
As I explained here, Freya allows the programmer to implement an interface type by delegating the implementation of methods from the interface to an instance of an already existing implementation. This trick is borrowed from Delphi, and it's an effective and easy technique for reusing interface implementations. Then, I used this example:
// WARNING: THE SYNTAX HAS CHANGED!!!
public
Foo = class(IEnumerable)
end;
implementation for Foo is
// A private instance field.
var Items: array of String := ['Freya', 'rules'];
// Just an implementation detail!
interface IEnumerable is Items;
end.
Our Foo class must implement the IEnumerable interface type, and it does it by delegating the implementation to a string array; all array types implement that interface, don't they? The delegation member contains a mention to the private field Items... but our real interest is the value stored in that field and, since our field is already initialized, it's highly probable that Items won't be referenced from other methods in this class. Why, then, should we need to declare Items at all?
This is a new alternative technique for delegating interface implementation:
implementation for Foo is
interface IEnumerable := ['Freya', 'rules!'];
end.
Now we can merge all what we need for the delegation in a single clause! Just think in all that can be done with this new feature. We have used a string list in our example, but it will be more common to find a regular constructor call as initializer:
implementation for Foo is
interface IEnumerator := new DriveEnumerator;
end.
In short, now we have two kinds of delegation clauses. One of them refers to a field or property in the same class. In this case, you can initialize the field or property in a constructor, or using a field or property initializer. The second and shorter form assigns directly a value in the delegation clause using an initializer. In this case, the compiler declares a hidden field inside the class and takes care of its initialization.
Labels: interface