3

I want to build some scala classes to model RDF. I have classes and properties. The properties are mixed in to the classes and can use the properties hashmap because of their self type.

As the classes get more properties I have to use a lot of mixins (50+) and I wonder if this is still a good solution performance wise?

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
roelio
  • 399
  • 2
  • 13

1 Answers1

8
scala> trait PropertyN { self: Dynamic =>
   | def props: Map[String, String]
   | def applyDynamic(meth: String)(args: Any*) = props get meth
   | }
defined trait PropertyN

Then you could create your class as follows:

scala> class MyClass(val props: Map[String, String]) extends PropertyN with Dynamic
defined class MyClass

Your class now has the methods you want it to:

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)

This is not very typesafe of course, but then neither is yours. Frankly, I think you are better off just using your map directly:

res0.properties get "a"

At least you are not suffering from any illusion of safety

oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449
  • Thanks, didn't know about the `Dynamic` type. If I can use it for my problem I will close this question. – roelio Feb 02 '12 at 13:24
  • I tried using your last suggestion but then I encounter a type problem see my other question: http://stackoverflow.com/q/9105791/730277 – roelio Feb 02 '12 at 13:32
  • I just meant not to declare `trait`s at all - instead of mixing in a method `getProperty1`, just grab the value from your map directly – oxbow_lakes Feb 02 '12 at 13:51
  • I understand what you mean, in the other question (see link in my previous comment) I don't use traits, but try to get the properties directly from the hashmap but then I encounter another [problem](http://stackoverflow.com/q/9105791/730277). – roelio Feb 02 '12 at 13:59