https://kotlinlang.org logo
Title
c

clubfan

03/30/2018, 12:41 PM
maybe zip and then flatmap?
d

Daniel

03/30/2018, 12:43 PM
Thank you and let's see about this with a short unit test
c

clubfan

03/30/2018, 12:46 PM
listOf("a", "b", "c").zip(listOf("d", "e")).flatMap(it.toList())
maybe? Haven't tested it though
d

Daniel

03/30/2018, 12:48 PM
Very close! This gets me to
<[a, d, b, e]>
On another note: the second list is always -1 the size of the first one, so this would be expect
list1.zip(list2).flatMap { it.toList() } + list1.takeLast(1)
would do it
c

clubfan

03/30/2018, 1:05 PM
fun <T> List<T>.merge(other : List<T>) : List<T> {
    val result = ArrayList<T>()
    for ( i in 0 .. maxOf(this.size, other.size)) {
        this.getOrNull(i)?.let { result.add(it) }
        other.getOrNull(i)?.let { result.add(it) }
    }
    return result
}
works, but it's not really idiomatic I think
and you can call it like this:
listOf("a", "b", "c").merge(listOf("d", "e"))
or this:
fun <T> List<T>.merge(other : List<T>) : List<T> {
    return this.mapIndexed{i, el -> other.getOrNull(i)?.let { listOf(el, it) } ?: listOf(el)}.flatten() + other.drop(this.size)

}
I'm pretty sure there's a better solution
Scala's zipAll would be great for this
i

ilya.gorbunov

03/30/2018, 2:57 PM
Please add your use case to this issue: https://youtrack.jetbrains.com/issue/KT-13017
Note that if the elements in lists are nullable, you won't be able to distinguish what the last
null
in
zipAll
means: either null last element or missing last element.
d

Daniel

03/30/2018, 9:44 PM
Thank you both for your replies! Currently I am settling for the .zip sulution with the awesome
require(other.size == size - 1)
function beforehand!