Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Generics treeview在kotlin中协变和逆变的正确使用_Generics_Kotlin_Variance_Contravariance - Fatal编程技术网

Generics treeview在kotlin中协变和逆变的正确使用

Generics treeview在kotlin中协变和逆变的正确使用,generics,kotlin,variance,contravariance,Generics,Kotlin,Variance,Contravariance,你好,stackoverflow社区 我使用泛型类型编写了一个方法。我有一种奇怪的感觉,它有点复杂。在互联网上,我发现了对变异和泛型变异的概念。但我试图把它做好却没有成功。有没有办法摆脱第二个(冗余的)泛型类型K fun <T, K> add(item: TreeItem<K>, startParent: TreeItem<T>, levelIndices: List<Int>) where K : T { var currentParen

你好,stackoverflow社区

我使用泛型类型编写了一个方法。我有一种奇怪的感觉,它有点复杂。在互联网上,我发现了对变异和泛型变异的概念。但我试图把它做好却没有成功。有没有办法摆脱第二个(冗余的)泛型类型K

fun <T, K> add(item: TreeItem<K>, startParent: TreeItem<T>, levelIndices: List<Int>) where K : T {
    var currentParent = startParent
    for ((counter, levelIndex) in levelIndices.withIndex()) {
        if (counter == levelIndices.size - 1) {
            @Suppress("UNCHECKED_CAST")
            currentParent.children.add(levelIndices.last(), item as TreeItem<T>)
            break
        }
        val positionEntryController = currentParent.children[levelIndex].value
        if (positionEntryController is PositionHeaderController) {
            currentParent = currentParent.children[levelIndex]
        } else {
            throw NotImplementedError()
        }
    }
}
fun add(项目:TreeItem,起始租金:TreeItem,级别索引:List),其中K:T{
var currentParent=startParent
对于levelIndex.withIndex()中的((计数器,levelIndex)){
if(计数器==levelIndexes.size-1){
@抑制(“未选中的_CAST”)
currentParent.children.add(levelIndexes.last(),项为TreeItem)
打破
}
val positionEntryController=currentParent.children[levelIndex].value
if(定位器控制器为定位器头控制器){
currentParent=currentParent.children[levelIndex]
}否则{
抛出NotImplementedError()
}
}
}

关键行在
@Suppress(“UNCHECKED_CAST”)
下,在这里我必须显式地进行强制转换。

我认为这应该允许您删除强制转换

fun <T> add(item: TreeItem<in T>, startParent: TreeItem<T>, levelIndices: List<Int>) {
fun add(项目:TreeItem,起始租金:TreeItem,级别索引:List){

不幸的是,这不起作用。
add(TreeItem(SubClass),TreeItem(Class),…)
不起作用。它应该是
out T
而不是
in T
,但我不明白为什么它会避免强制转换。