Walter: extend existing classes with new methods?

Ivan Senji ivan.senji_REMOVE_ at _THIS__gmail.com
Thu Aug 31 02:57:13 PDT 2006


Bill Baxter wrote:
> Marcio wrote:
>> Walter,
>>
>>    Do you plan to add the ability of adding methods to an existing 
>> class, from another module?
>>
>>    This ties to the issues raised at 
>> http://www.cs.princeton.edu/~dpw/popl/06/Tim-POPL.ppt and the fact 
>> that some languages/systems have had this capability for years 
>> (Smalltalk, for example, and more recently Ruby) with very beneficial 
>> results.
>>
> 
> Smalltalk and Ruby are both dynamically typed languages.  D is 
> statically typed -- that is the type of everything must be known at 
> compile-time, and in particular what methods are present must be known. 
>    AFIK, in D, like in C++, someobject.foo() either fails to compile, or 
> it successully calls foo() at runtime.  There is no runtime check to see 
> if the method exists or not before calling it.  What you're asking for 
> is a really big fundamental change to what D is.

Not really. It is possible to extend a type without the need for runtime 
checks. C# 3.0 has that feature and it is called extension methods.
Here is a little example:

static class Program
{
     static void Main(string[] args)
     {
         string s = "Hello, world";
         s.Print();
     }

     static void Print(this string s)
     {
         Console.WriteLine(s);
     }
}

There is nothing dynamic about that.

Actually D already has a feature to add methods to array types and it is
only a natural extension to allow it for other types.
The only thing compiler would have to do is for every
a.method(b);
check if there exists method(a,b); and translate the code to that.

This is how it works for arrays and it is one inconsistency just begging 
  to be resolved (and not my removing this feature, but by extending it 
to other types).




More information about the Digitalmars-d mailing list