Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codependent/circular generics loop

Tags:

java

generics

Problem:

I have two interfaces (here GenCarry and Gen):

public interface GenCarry<T extends Gen> {
    GenCarry<T> setGen(T gen);
}

public interface Gen<T extends GenCarry> {
    void applyOn(T carry);
}

It works when I ignore the 'rawtypes' Warning, but trying to complete them I don't get too far:

GenCarry<T extends Gen<GenCarry<T>>>
Gen<C extends GenCarry<Gen<C>>> -> error: not a valid substitute for the bounded parameter.

Question:

How would an interface like that look if complete - or is that even possible?

Is there a better approach to "generalize" an interface like that?

like image 734
TeNNoX Avatar asked Jun 20 '15 19:06

TeNNoX


1 Answers

You can define two type parameters:

public interface GenCarry<K extends GenCarry<K, T>, T extends Gen<T, K>> {
    GenCarry<K, T> setGen(T gen);
}

public interface Gen<K extends Gen<K, T>, T extends GenCarry<T, K>> {
    void applyOn(T carry);
}

class StringGenCarry implements GenCarry<StringGenCarry, StringGen> {
    @Override
    public StringGenCarry setGen(StringGen client) {
        ...
    }
}

class StringGen implements Gen<StringGen, StringGenCarry> {
    @Override
    public void applyOn(StringGenCarry network) {
       ...
    }
}
like image 125
M A Avatar answered Nov 12 '22 23:11

M A