-1

I have a sequence of Users in a collection

val users: Seq[User]

And I want to pass it into the Queue.enqueue method that takes:

def enqueue(elems : A*) 

I can foreach on my collection but I am sure there is a way to convert it right?

Also, what is A* called again?

cchantep
  • 9,118
  • 3
  • 30
  • 41
Blankman
  • 259,732
  • 324
  • 769
  • 1,199

3 Answers3

4

A* is a varargs type. To pass a collection to such a function, you can use the special vararg-expansion syntax, like this:

queue.enqueue(seq: _*) // If queue is of type Queue[User].

You can use this notation only if your collection is a Seq, or if it can be implicitly converted to a Seq.

marstran
  • 26,413
  • 5
  • 61
  • 67
2

As soon as A is a type parameter and is compatible (as for type constraints/variance) with User:

enqueue(users: _*)
cchantep
  • 9,118
  • 3
  • 30
  • 41
0

If the queue is mutable, you can use enqueue as pointed out by other answers or use ++=

scala> val mQueue = scala.collection.mutable.Queue[Int](1, 2, 3, 4, 5)
mQueue: scala.collection.mutable.Queue[Int] = Queue(1, 2, 3, 4, 5)

scala> val aSeq = Seq[Int](6, 7, 8, 9, 10)
aSeq: Seq[Int] = List(6, 7, 8, 9, 10)

scala> mQueue ++= aSeq
res26: mQueue.type = Queue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

If the queue is immutable, you have to use enqueue as following:

scala> val imQueue = scala.collection.immutable.Queue[Int](1, 2, 3, 4, 5)
imQueue: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3, 4, 5)

scala> imQueue.enqueue(aSeq.toList)
res32: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

In case of immutable, as the name suggests, imQueue is not updated, instead another immutable queue is returned.

scala> imQueue
res33: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3, 4, 5) // still original values
shaktimaan
  • 11,962
  • 2
  • 29
  • 33