如何将 Array<T?> 转换为 List<T>?

How to translate Array<T?> to List<T>?

我试过这个:

fun <T> computeMyThing(): List<T> {
    val array: Array<T?> = computeArray()
    return array.toList()
}

但是,毫不奇怪,它不会编译。

如果您确定数组中没有空值,您可以使用强制转换:

array.toList() as List<T>

如果确实存在空值,您需要将它们过滤掉:

array.filter { it != null } as List<T>

如您所见,您仍然需要投射。您还可以编写一个扩展方法来过滤掉空值和 returns 正确的类型:

fun <T> Array<T?>.filterNotNull(): List<T> {
    val destination = arrayListOf<T>()
    for (element in this) {
        if (element != null) {
            destination.add(element)
        }
    }
    return destination
}

然后就可以这样使用了:

array.filterNotNull()

编辑:Kotlin 中已经有一个 filterNotNull 方法。 IDE 没有提示,因为类型参数 T 有问题。 TT? 都可以为空。要修复它,请将方法签名更改为 fun <T : Any> computeMyThing(): List<T>,您将能够使用 array.filterNotNull() 而无需自己声明。