gpt4 book ai didi

scala - 使用大量带有 self 类型的 mixin

转载 作者:行者123 更新时间:2023-12-01 09:35:21 25 4
gpt4 key购买 nike

我想构建一些 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> 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)

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

res0.properties get "a"

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

关于scala - 使用大量带有 self 类型的 mixin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9112572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com