bennyhuo / KotlinTuples

Kotlin tuples.
MIT License
20 stars 0 forks source link

Allow generic programming with Tuples. #4

Open DavidPerezIngeniero opened 9 months ago

DavidPerezIngeniero commented 9 months ago

I've changed a little Generator.kt, so that all Tuple1, Tuple2, .... inherit from Tuple:

interface Tuple {
  fun data(): List<Any>
  val size: Int
}
infix fun <R, T> R.U(other: T) = tupleOf(this, other)
infix fun <R, T> R.V(other: T) = mutableTupleOf(this, other)
data class Tuple1<T1>(val _1: T1): Tuple {
  override val size = 1
  override fun data() = listOf(_1 as Any)
}
fun <T1> tupleOf(_1: T1) = Tuple1(_1)
fun <T> Tuple1<T>.toList() = listOf(_1)
fun <T1> Tuple1<T1>.toMutableTuple() = mutableTupleOf(_1)
infix fun <T, T1> Tuple1<T1>.U(other: T) = Tuple2(_1, other)
data class MutableTuple1<T1>(var _1: T1): Tuple {
  override val size = 1
  override fun data() = listOf(_1 as Any)
}

This allows me to do generic programming with a tuple of any size. Simple example:

fun <T: Tuple> showTuple(t: T): Unit {
    println("====")
    t.data().forEach {
        println(it.toString())
    }
}

fun main() {
    showTuple(tupleOf(1))
    showTuple(tupleOf(3, 2, 1))
}

even though I lose static type info when using generic programming.

Of course, I can provide a patch for this. For completeness, an empty Tuple could also be created. In Scala the empty tuple is written as: ()

object Tuple0: Tuple {
  override val size = 0
  override fun data() = listOf<Any>()
}
fun tupleOf() = Tuple0
DavidPerezIngeniero commented 9 months ago

Another improvement is the implementation of componentN(), so that Tuple2 is equivalent in usage to Pair.

bennyhuo commented 9 months ago

Another improvement is the implementation of componentN(), so that Tuple2 is equivalent in usage to Pair.

Kotlin compiler will generate componentN() functions for data classes. Tuple2 is almost the same with Pair.

DavidPerezIngeniero commented 9 months ago

Another improvement is the implementation of componentN(), so that Tuple2 is equivalent in usage to Pair.

Kotlin compiler will generate componentN() functions for data classes. Tuple2 is almost the same with Pair.

That's true. Sorry, I'm a newbie in Kotlin.

DavidPerezIngeniero commented 9 months ago

Are you interested in a patch or do I make my own fork?