【发布时间】:2020-12-13 02:43:25
【问题描述】:
在 Java 中,我们定义了一个 ObservableCollection.java,如下所示:
public class ObservableCollection<T> implements Collection<T> {
public SubscriptionHandle onElementAdded(Consumer<T> onAdded) {
// ...
}
}
还有一个返回 ObservableCollection 的 AgentService.java:
public interface AgentService {
ObservableCollection<? extends Agent> getAgents();
}
现在,我正在尝试在 Scala 项目中使用这个 ObservableCollection.java,如下所示:
def test(service: AgentService): Unit = {
val onAdded: Consumer[_ <: Agent] = ???
service.getAgents.onElementAdded(onAdded)
}
尝试这样做会导致以下编译错误:
type mismatch;
found : java.util.function.Consumer[_$1] where type _$1 <: com.xxxx.xx.xx.agent.Agent
required: java.util.function.Consumer[?0] where type ?0 <: com.xxxx.xx.xx.agent.Agent
service.getAgents.onElementAdded(onAdded)
^
one error found
这对我来说没有多大意义。有没有办法让它运行?
编辑:使用Cosumer[Agent]会导致以下错误:
type mismatch;
found : java.util.function.Consumer[com.xxxx.xx.xx.agent.Agent]
required: java.util.function.Consumer[?0] where type ?0 <: com.kuka.cc.si.agent.Agent
Note: com.xxxx.xx.xx.agent.Agent >: ?0, but Java-defined trait Consumer is invariant in type T.
You may wish to investigate a wildcard type such as `_ >: ?0`. (SLS 3.2.10)
service.getAgents.onElementAdded(onAdded)
^
one error found
【问题讨论】:
-
错误是真实的还是只是在某些 IDE 中? - 如果你有
Consumer[Agent],会发生什么? - 如果你像service.getAgents.asInstanceOf[ObservableCollection[Agent]](加上上一点)这样的脏演员会发生什么? -
@LuisMiguelMejíaSuárez 这是真的。
-
是的,错误是真实的。关于
Consumer[Agent]的用法:请参阅已编辑的问题。不过,有了脏演员,它就可以了!
标签: java scala type-conversion scala-java-interop bounded-wildcard