How to flatten a list that deep layer is not same:...
# getting-started
s
How to flatten a list that deep layer is not same: ex1:
Copy code
val deepList = listOf(
    listOf(
        listOf(-1, 0),
        listOf(1)
    ),
    listOf(2, 3),
    listOf(4, 5, 6)
)
println(deepList.flatten()) // [-1, 0, 1, 2, 3, 4, 5, 6]
ex2:
Copy code
val deepList = listOf(
    -1,
    listOf(listOf(listOf(0))),
    listOf(2, 3),
    listOf(4, 5, 6)
)
println(deepList.flatten()) // [-1, 0, 1, 2, 3, 4, 5, 6]
t
Flatten the list recursively:
Copy code
fun main() {
    val deepList = listOf(
        listOf(
            listOf(-1, 0),
            listOf(1)
        ),
        listOf(2, 3),
        listOf(4, 5, 6)
    )

    println(deepList.deepFlatten())
}

fun Iterable<*>.deepFlatten(): Iterable<*> = flatMap {
    when (it) {
        is Iterable<*> -> it.deepFlatten()
        else -> listOf(it)
    }
}
(Quickly cobbled together, not necessarily the best approch. YMMV)
🙌 1
u
It's a bit subtle though, because anything that happens to implement
Iterable
will silently get flattened. It also loses the type argument. I'd recommend not having heterogeneous lists like that if that can be avoided.
For example, maps and sets are also
Iterable
, but I doubt you would want
listOf(mapOf("foo" to 42)).deepFlatten()
to give you
listOf(Pair("foo", 42))
.
t
Regarding type, the list already is
List<Any>
, so there is no type to begin with. Regarding the use of
Iterable
, it depends on one's needs. You are right, however. To be safe, one might want seperate functions for list and set flattening. However,
Map
does not implement
Iterable
🤨
Copy code
val deepList = listOf(mapOf("foo" to 42)).deepFlatten()
println(deepList.deepFlatten())
// [{foo=42}]
u
Oh! I thought it did. My bad!
today i learned 1
That was just meant as an example though. My point is that
Iterable
is implemented by a lot of things.
t
Its a fair point! I just thought "broader = better!" without giving much thought to the consequences.