Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Scala's Queue.enqueue(iter: Iterable[B])?

Tags:

scala

In Scala's immutable.Queue, there are two methods both named enqueue:

  /** Creates a new queue with element added at the end
   *  of the old queue.
   *
   *  @param  elem        the element to insert
   */
  def enqueue[B >: A](elem: B) = new Queue(elem :: in, out)

  /** Returns a new queue with all elements provided by an `Iterable` object
   *  added at the end of the queue.
   *
   *  The elements are prepended in the order they are given out by the
   *  iterator.
   *
   *  @param  iter        an iterable object
   */
  def enqueue[B >: A](iter: Iterable[B]) =
    new Queue(iter.toList reverse_::: in, out)

I don't know how to resolve the ambiguity and call the second one. Here's what I have tried:

Welcome to Scala version 2.10.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_07).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import collection.immutable.Queue
import collection.immutable.Queue

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

scala> q.enqueue(Iterable(4))
res0: scala.collection.immutable.Queue[Any] = Queue(1, 2, 3, List(4))

scala> q.enqueue[Int](Iterable(4))
<console>:10: error: overloaded method value enqueue with alternatives:
  (iter: scala.collection.immutable.Iterable[Int])scala.collection.immutable.Queue[Int] <and>
  (elem: Int)scala.collection.immutable.Queue[Int]
 cannot be applied to (Iterable[Int])
              q.enqueue[Int](Iterable(4))
                       ^
like image 216
Tom Dong Avatar asked Jan 16 '13 02:01

Tom Dong


1 Answers

Tricky, tricky!

I created a ticket about it. You see, you have been misled by types!

scala> q.enqueue(scala.collection.Iterable(4))
res8: scala.collection.immutable.Queue[Any] = Queue(1, 2, 3, List(4))

scala> q.enqueue(scala.collection.immutable.Iterable(4))
res9: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3, 4)

The Iterable imported by default is the scala.collection.Iterable, which can be either mutable or immutable, but the immutable queue requires the immutable Iterable instead.

like image 101
Daniel C. Sobral Avatar answered Oct 05 '22 02:10

Daniel C. Sobral