2012-02-02 9 views
3

私は、RDFをモデル化するいくつかのスカラクラスを作りたいと思っています。私はクラスとプロパティを持っています。プロパティはクラスに混在しており、自己タイプのためにpropertiesハッシュマップを使用できます。自己タイプの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 

答えて

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

+0

私はあなたの最後の提案を使用してみましたが、私は他の質問を参照してください型の問題が発生しました:http://stackoverflow.com/q/9105791/730277 – roelio

+0

私は 'trait'sを全く宣言しないことを意味しました - メソッド 'getProperty1'は、マップから値を直接取得するだけです –

関連する問題