Tuple Interfaces (for data classes)


Wouldn’t it be opportune to add interfaces for tuples (with methods component1 etc) that data classes would automatically implement?

It would allow implementing a bunch of “structural” operations in a generic manner (for instance, swap for pairs).

A more complex use case I encountered recently: flatten left or right-associative pair-like hierarchies (e.g. X(1, X(2, X(3, Y)))).

Destructive method call

Agreed, TupleN interfaces (or something else, even) would be a nice addition to data classes. As it is there’s no way to take advantage of knowing that there are corresponding componentN getters.

Transforming data-classes with a function

This was discussed at some length on the Kotlin slack channel, where I proposed something similar.

The main issue is that data classes can have an unbounded number of components, so if you pick an arbitrary N (say 26) as the upper bound for the number of interfaces you will support, you will have different behaviour for data classes with N or fewer components than for data classes with more than N components.

I suggest an alternative pattern here: https://opencredo.com/the-destructor-pattern/

It’s also quite possible to declare TupleN classes yourself, and just declare your data classes as implementing them:

interface Tuple3<A, B, C> {
    fun component1(): A
    fun component2(): B
    fun component3(): C

data class Foo(val bar: String, val baz: String, val xyzzy: String): Tuple3<String, String, String>