使用大量自我类型的mixins

时间:2012-02-02 12:47:45

标签: scala rdf mixins

我想构建一些scala类来模拟RDF。我有课程和财产。这些属性被混合到类中,并且由于它们的自身类型,可以使用properties hashmap。

随着类获得更多属性,我必须使用大量mixins(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

1 个答案:

答案 0 :(得分: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 = MyClass@367013

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

当然,这不是很安全,但是你也不是。坦率地说,我认为你最好直接使用你的地图:

res0.properties get "a"

至少你没有任何安全幻觉

相关问题