How can I type for Collection<? super Some>?

45 views Asked by At

I have a method look like this.

public void some(..., Collection<? super Some> collection) {
    // WOOT, PECS!!!
    final Stream<Some> stream = getStream();
    stream.collect(toCollection(() -> collection));
}

And how can I make this method returns given collection instance type-safely?

I tried this.

public <T extends Collection<? super Some>> T some(..., T collection) {
    final Stream<Some> stream = getStream();
    stream.collect(toCollection(() -> collection)); // error.
    return collection; // this is what I want to do
}
1

There are 1 answers

2
Jin Kwon On

I found I have to do this

public <T extends Collection<Some>> T some(..., T collection) {
    final Stream<Some> stream = getStream();
    stream.collect(toCollection(() -> collection));
    return collection; // this is what I want to do
}

So that I can do this

List<Some> list = some(..., new ArrayList<>();

I wish I can explain.