2013-11-21 35 views
1

比方說,我有一個特點,Foo而這種特質需要一個泛型類型Bar,使Foo的定義將看起來就像多維衣衫襤褸的陣列,擴展通用特質

trait Foo[C <: Bar] { 
    def updateState(state : C) : C; 
} 

,和我有幾個類別action1action2,action3 ... action9,其延伸Foo

現在,假設我想顯式初始化這些動作的二維數組。

我試圖

Array[Foo[Bar]](
Array(new action1, new action2), 
Array(new action2, new action3)... 
) 
Array[Foo[Bar]](
Array[Foo[Bar]](new action1, new action2), 
Array[Foo[Bar]](new action2, new action3)... 
) 

和最與酒吧[Foo]添加[Foo[Bar]]無杆,使得主陣列Array[Array[Foo[Bar]]]等的排列

我找到一個解決問題的辦法通過使用

Array.ofDim[Foo[Bar]](size1, size2, size3) 

並手動初始化每個維度,但我想知道是否有某種方式來顯示citly初始化一個類型的二維數組,實現一個通用的特徵...是的,我知道這樣做有大約3個用例(不是真的,但它不是很常見),所以答案就像「你爲什麼這樣做?」。或者「有更好的方式囉嗦」不會太影響我。

回答

1

如果你可以定義項的指數和類的實例之間的關係,不是使用:

tabulate[T](n1: Int, n2: Int)(f: (Int, Int) ⇒ T) 

例子:

Array.tabulate(5, 5) { 
    case (i, j) => new action(i, j) 
} 

更新:

scala> :paste 
// Entering paste mode (ctrl-D to finish)  
trait Bar 
class Foo[C <: Bar] 

Array.tabulate(5, 5) { 
    case (i, j) => new Foo[Bar]() 
} 

// Exiting paste mode, now interpreting. 

defined trait Bar 
defined class Foo 
res1: Array[Array[Foo[Bar]]] = Array(Array([email protected], [email protected], [email protected], [email protected], [email protected]), Array([email protected], [email protected], [email protected], [email protected], [email protected]), Array([email protected], [email protected], [email protected], [email protected], [email protected]), Array([email protected], [email protected], [email protected], [email protected], [email protected]), Array([email protected], [email protected], [email protected], [email protected], [email protected])) 
+0

你能不能做一個二維的'[Foo [Bar]]的數組''使用這個?我看不出你的解釋或代碼如何暗示你可以。 –

+0

@theSilentOne發佈與控制檯輸出更新。 – Yuriy

+0

非常好,謝謝。 –

相關問題