2017-10-14 85 views
0

匹配在Scala中,你可以有通過對象的列表中的理解是迭代,然後讓值的陣列基於元素的屬性之一的類型?因此,假設我有元素的列表,每個元素都有一個屬性,該屬性可以是不同類型...階模式的理解

for (element <- elementList) element.attribute match { 
case a: Type1 => "Type1" 
case a => "All Types" 
} 

,然後將所得陣列將與值的數組一樣

Array("Type1", "Type1", "All Types", "Type1", "All Types", "All Types", "All Types", "All Types") 
+0

問題是什麼? – pamu

+0

我寫的不起作用。問題是如何製作陣列 –

回答

3

所有你需要做的就是yield結果......並可能轉換爲Array

(for (element <- elementList) yield element.attribute match { 
    case a: Type1 => "Type1" 
    case a => "All Types" 
}).toArray 
2

爲什麼你不使用從List(Element)地圖功能List(String)

如果您想從List(String)獲取數組,您可以使用函數toArray