bennyhuo / KotlinTuples

Kotlin tuples.
MIT License
20 stars 0 forks source link

Is there a way of getting the n-th element from a tuple? #2

Closed DavidPerezIngeniero closed 1 year ago

DavidPerezIngeniero commented 1 year ago

I'm coming from a Scala background. In Scala, every tuple implements this interface: https://www.scala-lang.org/api/2.13.5/scala/Product.html

That allows to get the n-th element and the arity of the tuple in a generic way.

Is there any base class common to all the tuples generated by this library?

bennyhuo commented 1 year ago

You can access to the n-th element by tuple._1 for the first element and tuple._2 for the second. You can also convert the tuple to a list.

I guess maybe you want to access them by tuple.nthElement(i) while i is a zero-based int, right?

DavidPerezIngeniero commented 1 year ago

Thanks for your valuable answer.

I've researched a little and discovered the component1(), component2() , .... methods, but it is a little cumbersome to make generic code that iterates over them, if reflection isn't used.

how do you know the number of elements it has?

the problem of converting to a list, is that all static type info becomes lost.

It would be nice to see an example of generic code that can work with a tuple of any size.

Is the type of tupleOf(1, 2.0, 3f, "hello") something like Tuple4<Int, Double, Float, String>?

DavidPerezIngeniero commented 1 year ago

I guess maybe you want to access them by tuple.nthElement(i) while i is a zero-based int, right?

Yes, it would be nice

DavidPerezIngeniero commented 1 year ago

You can access to the n-th element by tuple._1 for the first element and tuple._2 for the second. You can also convert the tuple to a list

Now that I think if I convert to a list, I can get the n-th element and the size of the tuple.

bennyhuo commented 1 year ago

how do you know the number of elements it has?

There is a size function youcan use to get the number of elements.

Is the type of tupleOf(1, 2.0, 3f, "hello") something like Tuple4<Int, Double, Float, String>?

That's right. And there are also Tuple10, ..., Tuple15 .... One Type for one size. They are all generated, and pretty straightforward.

DavidPerezIngeniero commented 1 year ago

Thanks for all your explanations. I consider interesting to complete the documentation with all the provided info