Thread overview
Default method implementations in interfaces?
Oct 23, 2015
pineapple
Oct 23, 2015
Alex Parrill
Oct 23, 2015
pineapple
Oct 23, 2015
Adam D. Ruppe
October 23, 2015
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?
October 23, 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.
}
October 23, 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 a mixin template together with your interface. Here's an example from my book:

http://arsdnet.net/dcode/book/chapter_06/09/multiple_inheritance.d

https://www.packtpub.com/application-development/d-cookbook

Notice that there's default implementations for each interface, you mix them in to get it all and can override individual names in the class too.
October 23, 2015
On Friday, 23 October 2015 at 15:07:05 UTC, Alex Parrill wrote:
> Use template mixins: http://dlang.org/template-mixin.html

On Friday, 23 October 2015 at 15:08:30 UTC, Adam D. Ruppe wrote:
> Use a mixin template together with your interface.

Awesome, thanks!

No way, though, to unite declaration and implementation? Feels a little too much like endless header files to me.
October 23, 2015
On 10/23/15 10:58 AM, 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?

If the idea is to have an implementation that *doesn't* get overridden, you can have final methods in an interface.

I know it's not what you asked for, but sometimes people may ask for something they know not realizing that something else may satisfy their needs :)

-Steve