-2

I want to create a tuple of size n, where n is an arbitrary integer (that is less than or equal to maximum tuple size). For example, with below data

val n = 3 //or 4 or 4 etc ; 
val y = 15
val z = 10
val e = 11

I am looking for a method like below

val x = genTuple(n,y,z,e)

that would return the following tuple

(15, 10, 11)

so how can create tuple of size n where the n can vary?

Davis Broda
  • 4,102
  • 5
  • 23
  • 37
mike
  • 35
  • 6
  • 2
    Tuples are immutable. You get what you construct, and that value never changes. There is no "populate"-phase. – Andrey Tyukin Jun 06 '18 at 22:06
  • Hi Andrey, I know Tuples are immutable and get what you construct. But my value of n depends on user input. so how can I create a tuple and then populate the values that is passed in. – mike Jun 06 '18 at 22:28
  • Then why do you want to use tuples for something they can't do? Why don't you just use `List.fill(n){value}` or something like that? – Andrey Tyukin Jun 06 '18 at 22:32
  • A tuple's type is the combination of the types of its elements: `(Char,String)` or `(Int,Int,Int)` or `(Boolean,Float)` or ... If a tuple has no elements then it has no type and it's not a tuple. Empty parentheses `()`, which looks like an empty tuple, is the value expression of type `Unit` (the only value of that type). – jwvh Jun 06 '18 at 22:35
  • Im using a tuple because i did not get to learning about list. So to understand you better can't use Tuples like this in scala??? – mike Jun 06 '18 at 22:45
  • 1
    If a method can return a tuple of various sizes then the actual return type is not `Tuple` but rather `Product with Serializable` instead. Bad news. You don't want to go there. – jwvh Jun 06 '18 at 22:53
  • I suggest to read an introduction to Scala that *at least* mentions `List`s. – Andrey Tyukin Jun 06 '18 at 23:07

1 Answers1

-2

To populate the tuple, create an iterator on a tuple and then use it.

To populate your example: val x = (15,10,11) then run the following expressions @ Scala REPLS

scala> val xiterator = x.productIterator
xiterator: Iterator[Any] = non-empty iterator

scala> for(element <- xiterator) println(element)
15
10
11

Your tuple may vary in size, this will work.

jwvh
  • 50,871
  • 7
  • 38
  • 64
Omprakash
  • 43
  • 5
  • This doesn't populate a tuple. It prints out the contents of an already populated tuple. – jwvh Jun 07 '18 at 06:50
  • It's available @ https://stackoverflow.com/questions/11305290/is-there-way-to-create-tuple-from-listwithout-codegeneration – Omprakash Jun 07 '18 at 12:00
  • Yes, that link tries to answer the same question asked here. Your answer does not. You'll note that none of the answers offered will result in a _true_ mixed-type tuple. It can't easily be done and it's not a good idea. – jwvh Jun 07 '18 at 16:40