2012-02-02 56 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