How to 'add' functions to existing type/class/struct/interface...

Matthew Ong ongbp at yahoo.com
Thu May 19 08:04:00 PDT 2011


Hi All/Walter Bright,

The ability is able to be model and done by JRuby and also Google Go.


Conversions
...
// this function is now available for the object type Sequence. Done 
outside of Sequence.d
func (s Sequence) MyFunction() string {
    //  My Function has access to all the public/internal data of the
    // Sequence here.
}
...
s Sequence;
s.MyFunction(); // now that can be used. Completelty new Function 
outside of Sequence.d

That is some how like JRuby ability to 'add' method into the java final 
String class without really touching that class String.

Interfaces and methods

Since almost anything can have methods attached, almost anything can 
satisfy an
interface. One illustrative example is in the http package, which 
defines the
Handler interface. Any object that implements Handler can serve HTTP 
requests.

It is not just entirely like java interfaces, but java has to somehow, 
code the api in a very strange pattern to support this.

I read from Adam that it is possible and is done within Phobos by D.
Could some one provide some sample code to explain that.

Mixin and Template does not quite fit there I think, in other 
language(Java/C#) are more for code reusing rather than code 'injection'.

Perhaps that is not the case within D as a limitation. Some code example 
would be really useful.



-- 
Matthew Ong
email: ongbp at yahoo.com



More information about the Digitalmars-d-learn mailing list