我試圖用新的關鍵字創建一個隊列..我爲可變和不可變隊列都做了這個。「new」關鍵字不能用於不可變的隊列
但是,當我用一成不變的隊列試過,提示錯誤:
<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()
誰能告訴我,爲什麼這樣?
隊列和大多數其他集合構造函數隱藏在標準庫中。相反,您應該使用工廠方法,例如'Queue [Int]()'或'Queue.empty [Int]'**,而不使用** new關鍵字。這是設計選擇。 –
但我想知道這個原因,爲什麼只有不可變隊列,可變隊列,這是好的。 – Rishi