如何调用Scala的Queue.enqueue(iter:Iterable [B])?

时间:2013-01-16 02:10:37

标签: scala

在Scala的immutable.Queue中,有两种名为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)

我不知道如何解决歧义,并打电话给第二个。这是我尝试过的:

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))
                       ^

2 个答案:

答案 0 :(得分:8)

棘手,棘手!

created a ticket关于它。你看,你被类型误导了!

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)

默认情况下导入的Iterablescala.collection.Iterable,可以是可变的也可以是不可变的,但不可变队列需要不可变 Iterable。< / p>

答案 1 :(得分:0)

Scala 2.13 弃用重载而支持 enqueueAll

同时,一种更简单的绕过方法是明确提及类型。

  val q = Queue[Vector[Int]]()

  val uQ: Queue[Vector[Int]] = q.enqueue(Vector(6))