Selftype: an idea from Scala for D2.0

Reiner Pope some at address.com
Sat May 26 22:26:56 PDT 2007


eao197 wrote:
> On Sun, 27 May 2007 05:23:55 +0400, Reiner Pope <some at address.com> wrote:
> 
>>>  class Sensor
>>>   {
>>>     mixin Subject!(Display, Sensor);
>>>      private char[] label_;
>>>     private double value_;
>>>      this( char[] label, double value )
>>>       {
>>>         label_ = label.dup;
>>>         value_ = value;
>>>       }
>>>      char[] label() { return label_; }
>>>     double value() { return value_; }
>>>     void value( double v ) { value_ = v; publish; }
>>>   }
>>>  class Display : Observer!(Sensor)
>>>   {
>>>     void notify( Sensor subj )
>>>       {
>>>         Stdout( subj.label )( " has value " )( subj.value ).newline;
>>>       }
>>>   }
>>
>> Using the syntax Subject is S automatically requires that any 
>> implementors of Subject!(Display, Sensor) inherit from Sensor. So why 
>> not simply make Sensor the inheritance root, as the mixin does? I 
>> don't see that any information is lost this way.
> 
> In that example Sensor doesn't inherit from Subject. The base type for 
> Sensor is Object.
> But may be situations in such a class must be inherited from some 
> domain-specific base class.

I simply can't see the situation you describe. Suppose we had a 
situation where you needed multiple classes to inherit from 
Subject!(Display, Sensor). Well, why would that be? Presumably so you 
can use them polymorhpically, perhaps something like the following:

void main()
{
     // Let's suppose we could actually have a base type
     // Subject!(Display, Sensor) from which everything
     // was derived. Suppose 'self' is possible.
     alias Subject!(Display, Sensor) SubjectType;
     SubjectType[] allSubjects = getListOfAllSubjects();

     Observer!(Sensor) myGenericObserver = new Display();
     foreach (s; allSubjects)
         s.subscribe(myGenericObserver);
}

For example, perhaps you have lots of things which need specific 
observers, and you additionally want to log everything using 
myGenericObserver. In that case, it is beneficial for all the classes to 
be inherited from Subject!(Display, Sensor).

But the condition 'Subject is S' already requires that 'this' for any 
descendant of Subject!(Display, Sensor) can be implicitly converted to 
Sensor. Which means that any class which inherits from Subject!(Display, 
Sensor) also inherits from Sensor. So you can rewrite my example above as

void main()
{
     // Now we don't need to have a base
     // type Subject!(Display, Sensor). Instead,
     // our base type is simply Sensor (which is
     // implemented with a mixin)
     Sensor[] allSubjects = getListOfAllSubjects();

     Observer!(Sensor) myGenericObserver = new Display();
     foreach (s; allSubjects)
         s.subscribe(myGenericObserver);
}

    -- Reiner



More information about the Digitalmars-d mailing list