用Java实现Kotlin接口的错误:返回类型不兼容

问题描述 投票:0回答:0

我尝试用 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 接口?

java kotlin generics collections covariance
© www.soinside.com 2019 - 2024. All rights reserved.