Default Implementation For an Interface

Lukasz wrzoski at gmail.com
Thu Feb 16 03:58:38 PST 2012


On Thursday, 16 February 2012 at 10:24:44 UTC, Jonathan M Davis 
wrote:
> On Thursday, February 16, 2012 11:11:20 Jacob Carlborg wrote:
>> You can create an abstract class that implements some parts of 
>> the
>> interface. Then the user (developer) is free to choose to 
>> inherit from
>> the interface or the abstract class.
>
> Which results in a classic problem that you run into in Java 
> all the time when dealing with event-based programming (since 
> it deals with events via interfaces). If you have a class that 
> only really needs to implement a couple of the functions from 
> the interface of an event listener, then you can derive from 
> the class which implements it and gives them all empty bodies. 
> But if you need your class to implement multiple such 
> interfaces, you can only do that with one of them, which gets 
> really annoying, because then you have to create a bunch of 
> empty method bodies yourself. It's one of the classic examples 
> where multiple inheritance would be desirable.
>
> The current situation in D is exactly the same (though, since 
> we don't have a swing equivalent, I don't think that it's 
> something that D programmers are frequently running into at the 
> moment). AIUI, Java is going to be adding the ability to give 
> interfaces default implementations such that that 
> implementation is effectively copy-pasted into your class when 
> you implement it and don't provide an implementation yourself 
> (rather than the function in your class overidding it as would 
> be the case with an abstract class). This nicely solves the 
> event listener problem, and D doesn't have that. I assume that 
> that's the sort of thing that the OP is looking for.
>
> Now, if you use template mixins, I believe that it's possible 
> to use that to mixin default implementations for the functions 
> in an interface, which should solve the problem for D. So, 
> that's probably good enough for D without having to make it so 
> that interface functions can have default implementations.
>
> - Jonathan M Davis

BlackHole from std.typeconst can be used for that purpose.



import std.typecons;
interface A
{
    void a();
    int b(void* arg);
}

interface B
{
    int c(string arg);
}

interface Common : A, B
{
}

class Good : BlackHole!Common
{
    override int b(void* arg)
    {
        return 0;
    }
}

void main()
{
    auto g = new Good;
    g.a();
    auto i = g.b(null);
    auto j = g.c("Hello");
}


More information about the Digitalmars-d-learn mailing list