How to create a tuple dynamically and add elements to it


Hi All,

I’m trying to create a function that creates tuple of different sizes.

For example

n = 3 or 4 or 5 etc

val x = Tuplen but this gives an error

and how can i add elements to it.



Can you provide a more detailed example of what you are trying to do? Most questions along these lines aren’t actually looking for a Tuple, but it would be helpful to see what you would want as the signature of this function, and how you would use it. (If you do want this, the answer is likely the Shapeless library.)


Putting myself out there, but i wonder why you’re using tuples when you could use and immutable List([Tuple2[String, A]). Why is it important to mutate the tuple, In dynamic languages this is not only frowed upon by not allowed. You can’t change a tuple in python, but you can copy to a new object. You can create a copy of it, but its a new type and there is an upper bound of 22, afaik. I think you’re looking at the wrong datatype. I think you need a really good use case for this or you’re going to run into problems. TupleN is a type, what problem are you trying to solve. I also hate the syntax, in your code if you extend your tuple type, do you know that you should be using t._5 or t._6 at runtime.

all that know more than more…please chime in :slight_smile:


Sorry List[(A, B)] probably won’t solve your problem, what is wrong with a Map.


I agree with Justin that shapeless is the solution, but if you want to solve this in pure scala/no libraries. What are you trying to do.