2011-11-27 74 views
4

我已經定義了在斯卡拉(2.9.1)一類,如下所示:如何初始化選項陣列爲無斯卡拉

class A(val neighbors: Array[Option[A]]) { 
    def this() = this(new Array[Option[A]](6)) 

    // class code here ... 
} 

我的問題是鄰居與空值,當我想它初始化初始化爲None。我想這一點,但是編譯器錯誤消息抱怨「找不到:鍵入無」:

class A(val neighbors: Array[Option[A]]) { 
    def this() = this(new Array[None](6)) 

    // class code here ... 
} 

我能做到這一點,這使期望的行爲,但它似乎並不很優雅:

class A(val neighbors: Array[Option[A]]) { 
    def this() = this(Array(None, None, None, None, None, None)) 

    // class code here ... 
} 

所以,我的問題是,這樣做的最好方法是什麼?

編輯:我指的是調用new A()時的行爲。

回答

9

做最簡單的方法,這將是

Array.fill(6)(None:Option[A]) 

另外,你可以改變你的類的構造函數採取這樣的默認參數:

class A(val neighbors: Array[Option[A]] = Array.fill(6)(None)) 
+2

如果'Array.fill'在'this()'構造函數中,不需要'None'上的類型註釋,因爲'neighbors'的類型已經是已知的,並且可以推斷出數組的類型。 –

+0

謝謝,我喜歡在構造函數中使用默認參數。 – astay13

2

也許這樣嗎?

def this() = this(Array.fill(6) {Option.empty})