🐦 Kotlin Intermediate

What is zip in Kotlin collections?

Answer

zip combines two collections into a list of Pairs, pairing elements at the same index. If the collections have different sizes, the result stops at the shorter one. Example: val pairs = listOf(1, 2, 3).zip(listOf("a", "b", "c")) gives [(1, "a"), (2, "b"), (3, "c")]. You can also pass a transform function: zip(other) { a, b -> a.toString() + b }. The inverse operation is unzip(), which splits a list of pairs into two separate lists.