2012-02-02 35 views
3

我想要構建一些scala類來爲RDF建模。我有課程和屬性。這些屬性被混合到類中,並且可以使用properties哈希映射,因爲它們的自我類型。使用大量混合自我類型

由於類獲得更多的屬性我不得不使用大量混入(50+)的,我不知道如果這仍是一個不錯的解決方案的性能明智?

trait Property 

trait Properties { 
    val properties = 
    new scala.collection.mutable.HashMap[String, Property] 
} 

abstract class AbstractClass extends Properties 

trait Property1 { 
    this: AbstractClass => 
    def getProperty1 = properties.get("property1") 
} 

trait Property100 { 
    this: AbstractClass => 
    def getProperty100 = properties.get("property100") 
} 

class Class1 extends AbstractClass 
    with Property1 with Property100 

回答

8
scala> trait PropertyN { self: Dynamic => 
    | def props: Map[String, String] 
    | def applyDynamic(meth: String)(args: Any*) = props get meth 
    | } 
defined trait PropertyN 

然後,你可以創建你的類,如下所示:

scala> class MyClass(val props: Map[String, String]) extends PropertyN with Dynamic 
defined class MyClass 

你的類現在有你想要的方式它:

scala> new MyClass(Map("a" -> "Hello", "b" -> "World")) 
res0: MyClass = [email protected] 

scala> res0.a 
dynatype: $line3.$read.$iw.$iw.res0.applyDynamic("a")() 
res1: Option[String] = Some(Hello) 

這是不是很類型安全的當然,但那也不是你的。坦率地說,我想你最好只使用直接在地圖:

res0.properties get "a" 

至少你不是從安全性的任何幻想痛苦

+0

謝謝,不知道了'Dynamic'類型。如果我可以用它來解決我的問題,我將結束這個問題。 – roelio 2012-02-02 13:24:43

+0

我試着用你最後的建議,但後來我遇到一個問題類型看我的其他問題:http://stackoverflow.com/q/9105791/730277 – roelio 2012-02-02 13:32:58

+0

我剛纔只是說,不申報'trait's在所有 - 而不是混合方法'getProperty1',只要抓住從地圖中值直接 – 2012-02-02 13:51:15

相關問題