0

I'm new to scala and I'm trying to figure out how tuple works. I'm trying to call the xth element of a tuplle where x is a variable but it seems not to work, how should I do?

for (x <- 1 to 2; j <- 0 to (N-1)) yield((j, index._x), (x-1,index._x))

In particular the index._x seem to not work

1
  • 1
    You can't do that, and is not the intended way of using tuples. Maybe you want a Vector instead. Commented Apr 6, 2022 at 16:47

1 Answer 1

1

It is possible to do this using the Product trait, though, as mentioned in the comment, this is not really a good idea or the intended way tuples are supposed to be used:

    val indexed = index.productIterator.toIndexedSeq
    for { 
      x <- 1 to 2
      j <- 0 until N
    } yield ((j, indexed(x-1)), (x-1, indexed(x-1))  

or better yet (get rid of indexed access, it's yuky):

   index.productIterator.take(2).toSeq.zipWithIndex
     .flatMap { case (value, index) => 
         (0 until N).map { j => ((j, value), (index, value)) }
     }

I'll say it again though: there is about 99% chance there is a better way to do what you are actually trying to do. Tuples are meant for grouping data, not iterating over it (use collections for that).

Sign up to request clarification or add additional context in comments.

1 Comment

The reason this is almost never a good idea is that you now no longer know the type of the field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.