1

val t = Vector(1 to 3: _*)
returns:

scala.collection.immutable.Vector[Int] = Vector(1, 2, 3)

val t = Vector(1 to 3)

returns :

scala.collection.immutable.Vector[scala.collection.immutable.Range.Inclusive] = Vector(Range(1, 2, 3))

How is the type conversion from scala.collection.immutable.Vector[scala.collection.immutable.Range.Inclusive]

to

 scala.collection.immutable.Vector[Int]

achieved using : _*

blue-sky
  • 51,962
  • 152
  • 427
  • 752

2 Answers2

2

You're using the companion object for Vector, namely the apply[A](elems: A*): Vector[A] method.

As you can see, the apply takes varargs as argument, so this:

val vec = Vector(1 to 3: _*)

expands the range (which is a sequence) to varargs, which ends up working effectively the same as typing:

val vec = Vector(1, 2, 3)

While this:

val rangeVec = Vector(1 to 3)

does not expand the range. That means the whole range is treated as one of the argument in varargs. So it's possible to do:

scala> val rangeVec = Vector(1 to 3, 6 to 10)
rangeVec: scala.collection.immutable.Vector[scala.collection.immutable.Range.Inclusive] = Vector(Range(1, 2, 3), Range(6, 7, 8, 9, 10))

to have a vector of ranges.

Fun fact: If you want to flatten the ranges from the range vector, it's quite easy:

scala> rangeVec.flatten
res4: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3, 6, 7, 8, 9, 10)
Patryk Ćwiek
  • 14,078
  • 3
  • 55
  • 76
1

1 to 3 creates a range object.

So Vector(1 to 3) creates a vector of range objects, not a vector of int.

_* extends the elements in the range into varargs, so it generates the vector you need.

Guillaume
  • 22,694
  • 14
  • 56
  • 70