jeggy
01/18/2021, 5:48 PMval myNumberList: List<Int> = listOf(1, 2, 3, listOf(4,5)).flatten()
ephemient
01/18/2021, 5:50 PMnanodeath
01/18/2021, 5:51 PMList<Any>
, which is hard to do much withephemient
01/18/2021, 5:51 PMfun <T> Iterable<Iterable<T>>.flatten(): List<T>
Casey Brooks
01/18/2021, 5:51 PMval myNumberList: List<Int> = listOf(1, 2, 3) + listOf(4,5)
?
But I’m pretty sure Kotlin would have to support union types in order for something like that to be possible without unsafe/unchecked typecastingJoel
01/18/2021, 6:33 PMlistOf(1, 2, 3, listOf(4,5))
is List<Any>
, so you've already lost type safety. Not ideal and probably not a candidate for std lib. Here is a horribly unsafe version that I would never use:
@Suppress("UNCHECKED_CAST")
@OptIn(ExperimentalStdlibApi::class)
fun <OUT> Iterable<Any?>.reallyFlatten(): List<OUT> = buildList {
this@reallyFlatten.filterNotNull().forEach {
when (it) {
is Iterable<*> -> addAll(it.reallyFlatten())
else -> add(it as OUT)
}
}
}
Called as listOf(1, 2, 3, listOf(4,5)).reallyFlatten<Int>()
.ephemient
01/18/2021, 6:55 PMfun <T> Iterable<Any?>.reallyFlatten(): List<T> = this.flatMap { it as? Iterable<T> ?: listOf(it as T) }
ephemient
01/18/2021, 6:57 PMfun <T> Iterable<Any?>.reallyReallyFlatten(): List<T> = this.flatMap { (it as? Iterable<Any?>)?.reallyReallyFlatten() ?: listOf(it as T) }
ephemient
01/18/2021, 6:58 PMNir
01/18/2021, 6:59 PMNir
01/18/2021, 6:59 PMNir
01/18/2021, 6:59 PMJoel
01/18/2021, 7:28 PMJoel
01/18/2021, 7:28 PMas?
return null
if the type cannot be cast? I thought it was a nullable cast i.e. cast if not null.Joel
01/18/2021, 7:29 PMnanodeath
01/19/2021, 1:39 AMas T?
ephemient
01/19/2021, 1:53 AMas? T
and as T?
have different behaviorephemient
01/19/2021, 1:59 AMnanodeath
01/19/2021, 2:29 AM