digitalmars.D.learn - Default method implementations in interfaces?
- pineapple (4/4) Oct 23 2015 Is it possible to have default method implementations in
- Alex Parrill (20/24) Oct 23 2015 Use template mixins: http://dlang.org/template-mixin.html
- pineapple (5/7) Oct 23 2015 Awesome, thanks!
- Adam D. Ruppe (8/12) Oct 23 2015 Use a mixin template together with your interface. Here's an
- Steven Schveighoffer (7/10) Oct 23 2015 If the idea is to have an implementation that *doesn't* get overridden,
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
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
On Friday, 23 October 2015 at 15:07:05 UTC, Alex Parrill wrote:Use template mixins: http://dlang.org/template-mixin.htmlOn 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
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
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