https://kotlinlang.org logo
#stdlib
Title
# stdlib
r

raulraja

02/26/2018, 7:07 PM
@mg6maciej Zipping lists is IMO better when preserving type information but it requires boilerplate for the different arities:
Copy code
data class Tuple3<A, B, C>(val a: A, val b: B, val c: C)

fun <A, B, C> List<A>.zip(g: List<B>, h: List<C>): List<Tuple3<A, B, C>> =
  this.zip(g).zip(h).map { (ab, c) ->
    val (a, b) = ab
    Tuple3(a, b, c)
  }

fun main (args: Array<String>) {

    val l1: List<Int> = listOf(1, 2, 3)
    val l2: List<Char> = listOf('1', '2', '3')
    val l3: List<String> = listOf("1", "2", "3")

    val zipped: List<Tuple3<Int, Char, String>> = l1.zip(l2, l3)

    println(zipped) //[Tuple3(a=1, b=1, c=1), Tuple3(a=2, b=2, c=2), Tuple3(a=3, b=3, c=3)]

}
g

gildor

02/27/2018, 1:27 AM
You don’t need
Tuple3
for this example. There is
kotlin.Triple
in stdlib
r

raulraja

02/27/2018, 4:26 AM
yeah, the point is that with TupleN or HList you can zip lists of different types preserving the type information and ideally a user would not need to create ext funs if there was an implicit conversion from a data class of N parameters and it's corresponding TupleN or HList of the same arity synthetically injected by the compiler. Such conversions are safe because there is an isomorphism between the Data class and the TupleN or Hlist. Then a user could just do:
Copy code
data class Account(val name: String, val description: String, val balance: Int)
val accounts: List<Account> = listOf("John", "Jane").zip(listOf("Savings", "Checking"), listOf(0, 1000)).map { it.toAccount() }
// [Account(John, Savings, 0), Account(Jane, Checking, 1000)]
This is the kind of stuff that would make working with Kotlin in environments like Spark where you heavily deal with poorly structured data a breeze.
You can still get to that right now but requires additional boilerplate of the user defining the additional
zip
functions and
toAccount
conversions
g

gildor

02/27/2018, 4:59 AM
I see your point, yeah would be interesting