www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Default method implementations in interfaces?

reply pineapple <meapineapple gmail.com> writes:
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?
Oct 23 2015
next sibling parent reply Alex Parrill <initrd.gz gmail.com> writes:
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. }
Oct 23 2015
parent pineapple <meapineapple gmail.com> writes:
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.
Oct 23 2015
prev sibling next sibling parent Adam D. Ruppe <destructionator gmail.com> writes:
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.
Oct 23 2015
prev sibling parent Steven Schveighoffer <schveiguy yahoo.com> writes:
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
Oct 23 2015