Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Delegates

Part of DelegateCategory

Description

If you have an interface with only 1 function, use a delegate instead because it is more flexible.

Example

import std.stdio;


interface Foo {
    int foo();
}

class MyClass : Foo {
    int foo() { 

        /* whatever */

        writefln("MyClass.foo() called") ;
        return 0;


    };
}


class ForgotFooClass {

  /* 
    Note that this class has the right functions to implement Foo, but
    I didn't add Foo interface to the list, so it's not compatible.
   */

int foo() {
 
        /* whatever */ 

        writefln("ForgotFooClass.foo() called") ;
        return 1; 
    };
}



class AnotherClass {
    int bar() { 
        /* whatever */ 
        writefln("AnotherClass.bar() called") ;
        return 2; 
    };
}


int main() {
    MyClass m = new MyClass;
    ForgotFooClass f = new ForgotFooClass;
    AnotherClass a = new AnotherClass;



//    doStuff1(a); /* can't call this */
/* 
Error:
 function doStuff1 (Foo f) does not match argument types (AnotherClass)
 cannot implicitly convert AnotherClass to Foo
*/

    doStuff1(m); /* legal call because MyClass derived from Foo */

//    doStuff1(f); /* can't call this because ForgotFooClass didn't derive from Foo */

//    doStuff2(f); /* can't call this */
/* 
Error:
 function doStuff2 (int delegate()d) does not match argument types (ForgotFooClass )
 cannot implicitly convert ForgotFooClass to int delegate()
*/

//    doStuff(a); /* can't call this because there is no matching function name for the Foo interface */

 /* 
  * these all work because the delegate can be extracted from the class without
  * it having to be part of the class declaration.
  */

    writefln();
    doStuff2(&m.foo);
    writefln();
    doStuff2(&f.foo);
    writefln();
    doStuff2(&a.bar);  /* the delegate can be a member with ANY name */

    return 0;


}

void doStuff1(Foo f) {
    writefln("doStuff1: f.foo() returned value = %d", f.foo()) ;
}

void doStuff2(int delegate() d) {
    writefln("doStuff2: d() returned value = %d", d()) ;
}

Source

Original contribution by Russ Lewis. Changed based on suggestions by Blandger.

Link http://www.dsource.org/tutorials/index.php?show_example=107
Edited by jcc7
Date/Time Thu Jul 29, 2004 9:53 pm