我尝试用 Java 实现一个 Kotlin 接口,所以我的接口看起来像这样:
interface KInterface {
val items: Collection<ItemInterface>
}
interface ItemInterface {
//
}
然后,在我的 Java 代码中,我有以下类:
class JavaItemImpl implemets ItemInterface {
//
}
class JavaImpl implements KInterface {
private List<JavaItemImpl> items;
@Override
public List<? extends ItemInterface> getItems() {
return items;
}
}
Kotlin Collection 是协变的
public interface Collection<out E> : Iterable<E>
,所以我假设 List<? extends ItemInterface>
在实现 Kotlin 接口时会起作用。
但是,这段代码给我一个错误:'getItems()' in 'JavaImpl' clashes with 'getItems()' in 'KInterface'; attempting to use incompatible return type
.
一种解决方法是在
items
可变集合中制作 KInterface
并添加类型投影,如下所示:
val items: MutableCollection<out ItemInterface>
但是我想知道,有没有其他方法可以在不使 Kotlin 集合可变的情况下实现这样的 Kotlin 接口?