Better Tuples

In Kotlin, you can already do stuff like "hello" to "hi" to "greetings", which will result in a Pair<String, Pair<String, String>>, now you can do this continually to get a tuple of x. This means there is no need for the Triple tuple.

To use this easily, add some utility functions. Like Pair#forEach, which would like a bit like this:

fun <A, B> Pair<A, B>.forEach(context: (Any?) -> Unit) {
    for (any in arrayOf(first, second)) {
        if (any is Pair<*, *>) {
            any.forEach(context)
        } else {
            any.apply(context)
        }
    }
}

Tuple creation from a List could look something like this.

fun tupleOf(list: List<Any?>): Pair<Any?, Any?> {
    return if (list.size >= 2) 
        Pair(list[0], tupleOf(list.drop(1))) 
    else
        Pair(list.getOrNull(0), list.getOrNull(1))
}

Why not just use listOf(...) instead? Why do you need a tuple object here?

6 Likes

This sounds like cons cell–based linked lists.

1 Like

If not for the automatic bounds checking, it would be great if tuples were subclasses of Array<Any?>