如何展平超过 2 个嵌套的数组

how to flatten more than 2 array nested

我是 Kotlin 的新手。当我了解 flatten 函数时

Returns a single list of all elements from all arrays in the given array.

说明that.It在数组嵌套数组中工作。但是,超过 3 个数组怎么样。喜欢:

val testArray = listOf(listOf(1,2,3), listOf(4,3,9, listOf(3,3,6)))

我想要的输出是:

[1, 2, 3, 4, 3, 9, 3, 3, 6]

所以,有人可以帮助我吗? 谢谢

这应该适用于无数嵌套数组。


fun <T> Iterable<T>.enhancedFlatten(): List<T> {
    val result = ArrayList<T>()
    for (element in this) {
        if (element is Iterable<*>) {
            try {
                result.addAll(element.enhancedFlatten() as Collection<T>)
            } catch (e: Exception) {
                println(e)
            }
        } else {
            result.add(element)
        }
    }
    return result
}
fun List<*>.deepFlatten(): List<*> = this.flatMap { (it as? List<*>)?.deepFlatten() ?: listOf(it) }