I'm trying create an instance of a class and mix in certain traits based on certain conditions. So Given:
class Foo
trait A
trait B
I can do something like
if (fooType == "A")
new Foo with A
else if (footType == "B")
new Foo With B
That works just fine for a simple case like this. My issue is that multiple traits can be mixed into the same instance based on other conditions, and on top of that the class being instantiated has a fair amount of parameters so this leads to a pretty ugly conditional block.
What I would like to do is determine the traits to be mixed in before hand something like this (which I know is not legal scala code):
val t1 = fooType match {
case "a" => A
case "b" => B
}
val t2 = fooScope match {
case "x" => X
case "y" => Y
}
new Foo with t1 with t2
Where A, B, X, and Y are all previously defined traits, and fooType and fooScope are inputs to my function. I'm not sure if there is anything I can do which is somewhat similar to the above, but any advice would be appreciated.
Thanks
I believe what you want to do is not possible. In Scala the type of an object has to be known at compile time, so
new Foo with A
works butnew Foo with t1
will not becauset1
is resolved only at run time.