I'm guessing this is something that has been discu...
# announcements
j
I'm guessing this is something that has been discussed before, so I'm asking if anyone has a YouTrack for it somewhere. Does Kotlin have any plans to make something that looks like this possible?
Copy code
val myNumberList: List<Int> = listOf(1, 2, 3, listOf(4,5)).flatten()
e
what would the type of that flatten method look like?
n
yeah...the first list is type
List<Any>
, which is hard to do much with
e
for reference, the existing flatten method has type
fun <T> Iterable<Iterable<T>>.flatten(): List<T>
c
Why not just do
val 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 typecasting
👍 1
j
listOf(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:
Copy code
@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>()
.
e
equally unsafe, just shorter:
Copy code
fun <T> Iterable<Any?>.reallyFlatten(): List<T> = this.flatMap { it as? Iterable<T> ?: listOf(it as T) }
heck, you could even go so far as
Copy code
fun <T> Iterable<Any?>.reallyReallyFlatten(): List<T> = this.flatMap { (it as? Iterable<Any?>)?.reallyReallyFlatten() ?: listOf(it as T) }
but yes, no type safety at all and not suitable for stdlib
n
the closest to ever doing something like this in real life I've come is flattening out jsons for certain purposes
but, as mentioned, you would have nested data structures using sealed classes
and it's very niche
j
@ephemient lololol
Wait, does
as?
return
null
if the type cannot be cast? I thought it was a nullable cast i.e. cast if not null.
n
that might be
as T?
e
@nanodeath no,
as? T
and
as T?
have different behavior
n
I'm aware