我想构建一些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
Run Code Online (Sandbox Code Playgroud)
scala> trait PropertyN { self: Dynamic =>
| def props: Map[String, String]
| def applyDynamic(meth: String)(args: Any*) = props get meth
| }
defined trait PropertyN
Run Code Online (Sandbox Code Playgroud)
然后你可以创建你的类,如下所示:
scala> class MyClass(val props: Map[String, String]) extends PropertyN with Dynamic
defined class MyClass
Run Code Online (Sandbox Code Playgroud)
您的班级现在拥有您想要的方法:
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)
Run Code Online (Sandbox Code Playgroud)
当然,这不是很安全,但后来也不是.坦率地说,我认为你最好直接使用你的地图:
res0.properties get "a"
Run Code Online (Sandbox Code Playgroud)
至少你没有任何安全错觉
| 归档时间: |
|
| 查看次数: |
195 次 |
| 最近记录: |