簡體   English   中英

“new”關鍵字不適用於不可變隊列

[英]“new” Keyword doesn't work with immutable Queue

我嘗試用新的Keyword創建一個Queue ..我為可變和不可變的Queue做了它。

但是當我嘗試使用不可變隊列時,它會出錯:

<console>:8: error: constructor Queue in class Queue cannot be accessed in object $iw
 Access to protected constructor Queue not permitted because
 enclosing class object $iw in object $iw is not a subclass of 
 class Queue in package immutable where target is defined
       val a=new Queue[Int]()
             ^

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

scala> val a=new Queue[Int]()
<console>:8: error: constructor Queue in class Queue cannot be accessed in object $iw
 Access to protected constructor Queue not permitted because
 enclosing class object $iw in object $iw is not a subclass of 
 class Queue in package immutable where target is defined
       val a=new Queue[Int]()

但是當我嘗試使用可變隊列,不可變堆棧,可變堆棧的代碼時...它運行良好

scala> import scala.collection.mutable.Queue
import scala.collection.mutable.Queue

scala> val a=new Queue[Int]()
a: scala.collection.mutable.Queue[Int] = Queue()



scala> import scala.collection.immutable.Stack
import scala.collection.immutable.Stack

scala> val a=new Stack[Int]()
a: scala.collection.immutable.Stack[Int] = Stack()


scala> import scala.collection.mutable.Stack
import scala.collection.mutable.Stack

scala> val a=new Stack[Int]()
a: scala.collection.mutable.Stack[Int] = Stack()

誰能告訴我,為什么會這樣?

從快速查看源代碼開始 ,我冒昧地認為不可變版本基本上是通過一些List的,這些List根據需要進行調整,以便在讀取寫入 (隊列/出隊)之間提供良好的性能。

這與其他集合非常不同,因為它需要將List s作為class構造函數的參數。
另一方面,伴隨對象通過接受Queue內容的可變數量的初始值,提供與其他集合一致的公共工廠方法。

缺少的是類的公共構造函數,它將模仿伴隨對象apply調用,獲取初始值,並使用它們構建“enque / dequeue” Lists

也許這不是必要的,或者它是一種疏忽,或者是一個我無法弄清楚的更深層次的問題。

編譯器已經告訴你它為什么不起作用,因為結構符號是protected 您必須使用隨immutable.Queueapply方法來創建immutable.Queue

val queue = immutable.Queue(1,2,3)

我將這個問題解釋為“為什么構造函數受到保護”。 我們只能猜測,但我傾向於認為這是一個簡單的疏忽。 作為一種風格問題,通常最好使用伴隨對象來實例化集合,但考慮到您也可以直接實例化其他具體集合,這應該與Queue 換句話說,我絕對認為Queue應該有這個沒有arg構造器來創建一個空隊列,如果只是為了一致性:

class Queue[+A] extends ... {
  ...
  def this() { this( Nil, Nil ) }
  ...
}

但這是非常主觀的。

我猜這是因為鼓勵使用empty來創建void不可變集合,因為它避免了開銷(如果你多次這樣做)並且最大限度地利用不變性。 不需要每次都創建新實例,因為“世界上只有一個空隊列”。 對於可變集合,很明顯這不起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM