【问题标题】:Using lots of mixins with self type使用大量带有 self 类型的 mixin
【发布时间】:2012-02-25 02:55:25
【问题描述】:

我想构建一些 scala 类来建模 RDF。我有类和属性。这些属性混合在类中,并且可以使用properties hashmap,因为它们的自身类型。

随着类获得更多属性,我不得不使用很多 mixin(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

【问题讨论】:

    标签: scala rdf mixins


    【解决方案1】:
    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"
    

    至少你没有任何安全的幻觉

    【讨论】:

    • 谢谢,不知道Dynamic 类型。如果我可以用它来解决我的问题,我会关闭这个问题。
    • 我尝试使用您的最后一个建议,但后来遇到类型问题,请参阅我的另一个问题:stackoverflow.com/q/9105791/730277
    • 我的意思是根本不声明traits - 而不是混入一个方法getProperty1,直接从你的地图中获取值
    • 我明白你的意思,在另一个问题中(请参阅我之前评论中的链接)我不使用特征,但尝试直接从哈希图中获取属性,但后来我遇到另一个 @987654322 @.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多