baba.kabira
baba.kabira

Reputation: 3171

Adding a specific Trait to a Class at runtime

I have a trait "Foo" with some methods. I want to mix this trait to any class. But I dont want to write something like

val b = new Bar with Foo

I need something like where I just pass a class and it is mixed with Foo. I want to mix with this trait only i.e it is fixed that all classes should be mixed with Foo trait only.

val b = new Factory(Bar) //Factory returns instance with trait Foo

I found this post but I am not convinced.

Something like this is possible in scala?

Upvotes: 3

Views: 1507

Answers (1)

Kevin Wright
Kevin Wright

Reputation: 49705

The current best solution is to implement Foo something like this:

class Foo(bar:Bar) {
    ...
}
object Foo {
    def apply(bar:Bar) = new Foo(bar)
    implicit def backToBar = this.bar
}

Then use it as

val foo = Foo(myBar)

For any method names that are shared between Foo and Bar, the version in Foo will be used (as with overloading in a mixin). Any other methods, the variant on Bar will be used.

The technique isn't perfect, methods in Bar will only ever call other methods defined in Bar, and never "overloads" defined in Foo. Otherwise, it's pretty close to your needs.

Upvotes: 4

Related Questions