简体   繁体   English

如何使协变消费者 <? extends Base> 工作?

[英]How to make covariant Consumer<? extends Base> work?

This is the smallest code sample I could come up with to illustrate the problem: 这是我可以用来说明问题的最小代码示例:

public void consumeDerived(Consumer<Derived> derivedConsumer, Derived derivedParameter) {
    consumeBase(derivedConsumer, derivedParameter);
}

public void consumeBase(Consumer<? extends Base> baseConsumer, Base baseParameter) {
    baseConsumer.accept(baseParameter);
}

The idea is that the call to consumeDerived simply gets passed along to the consumeBase method. 这个想法是,对consumeDerived的调用只是传递给了consumeBase方法。 To my understanding, the call baseConsumer.accept() should be able to take type Base or type Derived extends Base . 据我了解,调用baseConsumer.accept()应该能够使用Base类型或Derived extends Base类型。

However I get the error: java: incompatible types: Base cannot be converted to capture#1 of ? Base 但是我得到了错误: java: incompatible types: Base cannot be converted to capture#1 of ? Base java: incompatible types: Base cannot be converted to capture#1 of ? Base . java: incompatible types: Base cannot be converted to capture#1 of ? Base

What do I need to do to make this work? 我需要做些什么才能使这项工作?

The problem is that Consumer<? extends Base> 问题是Consumer<? extends Base> Consumer<? extends Base> is a consumer of something which extends a Base . Consumer<? extends Base>是的东西 ,其延伸的消费者Base It may be a Consumer<Derived> , and that wouldn't be able to accept a Base as an argument - it's not specific enough. 它可能是Consumer<Derived> ,并且不能接受Base作为参数-不够具体。

You can add a generic type parameter to solve this: 您可以添加通用类型参数来解决此问题:

public <T extends Base> void consumeBase(Consumer<T> baseConsumer, T baseParameter) {
    baseConsumer.accept(baseParameter);
}

It's also worth noting that consumeDerived is now superfluous. 还要指出的是, consumeDerived是多余的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM