2013-10-12 47 views
0

因此,這裏是我有:運行實例在Scala中沒有類型參數

type CompType = Manifest[_ <: Component] 

type EntityType = HashSet[CompType] 
type CompSet = HashSet[Component] 

val type_map = new HashMap[String, EntityType] 
val entity_map = new HashMap[EntityID, CompSet] 

def createEntityType(type_name: String) = { 
    val ent_id = new EntityID 
    val ent_type: CompSet = 
    type_map(type_name) map (c_type => c_type.erasure.newInstance()) 

    entity_map += (ent_id -> ent_type) 

    ent_id 
} 

但正如你所看到的,map功能不創建一個CompSet,它會創建一個HashSet[Any]

有什麼辦法可以解決這個問題嗎?

整個問題的關鍵是保存對象類型以便稍後在程序中進行實例化,但是我無法實現此功能,並且所有反射示例都希望通過_.asInstanceOf[SomeClassType]來投射某種類型的參數。

回答

0
type_map(type_name) map (c_type => c_type.erasure.newInstance().asInstanceOf[Component]) 

BTW,Manifest在2.10中已棄用,您應該使用ClassTag s和TypeTag s代替。

+0

有沒有什麼辦法可以確保每個實例都被實例化爲它的子組件?另外,謝謝你,我會研究'ClassTag'和'TypeTag'。 – SethSR

+0

如果你的'Manifest'包含真實類的信息而不是'Component',那麼情況就是這樣。 'asInstanceOf'只是一個類型轉換,它並不奇蹟般地使'newInstance()'返回一個基類的實例,特別是當它不可能時(如果Component是一個接口或一個抽象類)。 –

+0

回想起來,這是有道理的。至少,我已經得到了它的工作。在開始詢問任何問題之前,我會嘗試使用'ClassTag'和'TypeTag'。謝謝。 – SethSR