Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composition and generics

I'm trying to solve this "composition + generics" situation, and make PostCompany.send(msg) be compatible with the type passed/injected to the class.

What could I change to allow both Fedex and FedexPlus being used as generic Types at PostCompany class, since Fexed's send method expects String as parameter and FeexPlus expects Integer?

interface Poster<T> {
    void send(T msg);
}

class Fedex implements Poster<String> {

    @Override
    public void send(String msg) {
        // do something
    }
}

class FedexPlus implements Poster<Integer> {

    @Override
    public void send(Integer msg) {
        // do something
    }
}

class PostCompany<P extends Poster> {

    private final P poster;

    public PostCompany(P poster) {
        this.poster = poster;
    }

    public void send(??? msg) { // <-- Here 
        this.poster.send(msg);
    }
}
like image 503
VeryNiceArgumentException Avatar asked Jan 28 '23 14:01

VeryNiceArgumentException


1 Answers

You missed the type of a Poster

class PostCompany<T, P extends Poster<T>> {
    public void send(T msg) { // <-- Here 
        this.poster.send(msg);
    }
}

But it actually better to just type the type of the object

class PostCompany<T> {

    private final Poster<T> poster;

    public PostCompany(Poster<T> poster) {
        this.poster = poster;
    }

    public void send(T msg) { // <-- Here 
        this.poster.send(msg);
    }
}

Since you will always be using the interface methods of Poster

like image 105
Marcos Vasconcelos Avatar answered Jan 30 '23 04:01

Marcos Vasconcelos