Generics 我如何投a<;输出任何>;泛型类型转换为特定类型,以便可以在泛型函数中运行?

Generics 我如何投a<;输出任何>;泛型类型转换为特定类型,以便可以在泛型函数中运行?,generics,kotlin,Generics,Kotlin,我有一个函数replaceCollection,它需要两个MongoCollection来执行替换 函数声明如下所示 private-suspend-fun-replaceCol(旧的:MongoCollection,新的:MongoCollection,会话:ClientSession) 当我在函数中放入两个MongoCollection时,它可以正常工作。但是,我有一个要替换的集合列表,但是我找不到方法强制转换,以确保编译器它们具有相同的类型,以便可以在泛型函数replaceCol中运行 /

我有一个函数
replaceCollection
,它需要两个
MongoCollection
来执行替换

函数声明如下所示

private-suspend-fun-replaceCol(旧的:MongoCollection,新的:MongoCollection,会话:ClientSession)

当我在函数中放入两个
MongoCollection
时,它可以正常工作。但是,我有一个要替换的集合列表,但是我找不到方法强制转换
,以确保编译器它们具有相同的类型,以便可以在泛型函数
replaceCol
中运行

//oldCols[i] and newCols[i] always have the same generic type 
val oldCols: Array<MongoCollection<out Any>> = ...
val newCols: Array<MongoCollection<out Any>> = ...

for(i in prodCols.indices) {
    replaceCol(preProdCols[i], prodCols[i], session)
}   

/* error on the line of replaceCol
Type inference failed: Cannot infer type parameter T in //...
None of the following substitutions
(
MongoCollection<CapturedTypeConstructor(out Any)>,
MongoCollection<CapturedTypeConstructor(out Any)>,
ClientSession
)
(
MongoCollection<CapturedTypeConstructor(out Any)>,
MongoCollection<CapturedTypeConstructor(out Any)>,
ClientSession
)
can be applied to
(
MongoCollection<out Any>,
MongoCollection<out Any>,
ClientSession!
)
*/
//oldCols[i]和newCols[i]始终具有相同的泛型类型
val oldCols:Array=。。。
val newCols:数组=。。。
对于(i在产品指数中){
replaceCol(预调试[i],产品[i],会话)
}   
/*replaceCol行上的错误
类型推断失败:无法在//中推断类型参数T。。。
以下替代品均不适用
(
MongoCollection,
MongoCollection,
客户会议
)
(
MongoCollection,
MongoCollection,
客户会议
)
适用于
(
MongoCollection,
MongoCollection,
客户会议!
)
*/

如果您100%确定相同索引上的集合具有相同的泛型类型,则可以使用未选中强制转换:

fun <T> replaceArray(old: Array<T>, new: Array<T>) {
    old[0] = new[0]
}

fun <T> forceReplace(old: Array<T>, new: Array<*>) {
    @Suppress("UNCHECKED_CAST")
    replaceArray(old, new as Array<T>)
}

fun main() {
    val old = arrayOf<Array<out Any>>(
        arrayOf(0),
        arrayOf("!")
    )
    val new = arrayOf<Array<out Any>>(
        arrayOf(1),
        arrayOf("?")
    )
    for (i in old.indices) {
        forceReplace(old[i], new[i])
    }
}
fun-replaceArray(旧:数组,新:数组){
旧的[0]=新的[0]
}
替换(旧:阵列,新:阵列){
@抑制(“未选中的_CAST”)
replaceArray(旧的,新的作为数组)
}
主要内容(){
val old=arrayOf(
arrayOf(0),
排列(“!”)
)
val new=arrayOf(
第(1)款,
排列(“?”)
)
用于(旧索引中的i){
强制替换(旧[i],新[i])
}
}

但是,解决问题的最佳方法仍然是重新设计逻辑,这样就不需要这样的解决方法。

您是否在函数中修改了
MongoCollection
s?你能重写它,使它不修改它们吗?(将
old:MongoCollection
替换为
old:MongoCollection
可以解决问题)@ardenit不,我不这么认为。我正在使用
newCol
MongoCollection
对象从数据库检索信息,并将信息放入
oldCol
中。我不知道您的结构和代码到底是什么样的,但如果您知道泛型参数T的具体类型(或至少其范围),您可以提前使用sealed类将这些类似的类分组在一起,并确保它们都实现了sealed类,这样您就可以使用泛型了。谢谢,但是定义
fun-forceReplace(旧:数组,新:数组)
,对我来说没有多大意义,虽然函数应该包含两个具有相同泛型类型的数组,但您不需要更改函数
replaceArray
的定义与函数一样
forceReplace
可能是私有函数,或者您可以在循环中执行未经检查的强制转换。您对存储此类集合的更好设计有何建议?我有~10个oldCol和~10个newCol,我希望以后能有更多。正如建议的那样,如果您知道哪些类型可以用作泛型参数,可以使用密封类。