Default method implementations in interfaces?

Alex Parrill via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Oct 23 08:07:00 PDT 2015


On Friday, 23 October 2015 at 14:58:43 UTC, pineapple wrote:
> Is it possible to have default method implementations in 
> interfaces à la Java in D? Or some equivalent that allows 
> multiple inheritance without a bunch of identical copypasted 
> method bodies?

Use template mixins: http://dlang.org/template-mixin.html

interface MyInterface {
     void foo();
     int bar();
}

mixin template MyInterfaceDefaultImpl() {
     void foo() {
         // put code here
     }
     int bar() {
         // put code here
     }
}

class MyClass : MyInterface {
     mixin MyInterfaceDefaultImpl!(); // Similar to inserting the 
body of `MyInterfaceDefaultImpl` at this point.
     mixin MyOtherInterfaceDefaultImpl!(); // Can put any amount 
of them here.
}


More information about the Digitalmars-d-learn mailing list