0

I would like to get something like: Seq((1,2), (42, 45), (54, 52), ...).
In other words I would like to create Seq of length n with pairs of random integers.

I tried to to do something like:
(1 to n).toSeq.map(_ -> (scala.util.random.nextInteger(),scala.util.random.nextInteger() )) However, it returns some IndexedSeq instead of Seq.
Could anyone help me, please?

tomek.xyz
  • 129
  • 7
  • 2
    It isn't "instead". [IndexedSeq](https://www.scala-lang.org/api/2.12.3/scala/collection/IndexedSeq.html) is a subtype of `Seq`. It just provides the additional information that the indexed accesses are fast. If you want to erase the too exact type, you can use [type ascription](https://docs.scala-lang.org/style/types.html#ascription). – Andrey Tyukin Aug 31 '20 at 16:43
  • Or you can put the `toSeq` after the `map`. In any case, it shouldn't matters and you shouldn't be using **Seq** anyways. – Luis Miguel Mejía Suárez Aug 31 '20 at 16:48
  • 2
    @LuisMiguelMejíaSuárez That doesn't "help": the inferred type of `.toSeq` in the end is `IndexedSeq` :) How did you mean it that one "shouldn't be using Seq anyways"? – Andrey Tyukin Aug 31 '20 at 16:50
  • 1
    @AndreyTyukin oh, didn't know `toSeq` wasn't returning a `Seq`, weird. - For the second point, take a look to [this](https://gist.github.com/djspiewak/2ae2570c8856037a7738#problems). – Luis Miguel Mejía Suárez Aug 31 '20 at 16:56
  • 2
    You might find [this question](https://stackoverflow.com/q/56147577/4993128), and its answers, informative. – jwvh Aug 31 '20 at 17:08

1 Answers1

1

As explained in the comments, it is OK that it returns IndexedSeq because this is a subtype of Seq. But Scala has a library method called fill that will do what you want:

Seq.fill(n)((scala.util.Random.nextInt(), scala.util.Random.nextInt()))

However it is probably best to be explicit about the actual type you want (Vector, List etc.):

Vector.fill(n)((scala.util.Random.nextInt(), scala.util.Random.nextInt()))

This can still be assigned to a Seq but you can choose the appropriate implementation for your application.

Tim
  • 26,753
  • 2
  • 16
  • 29