Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a specific Trait to a Class at runtime

Tags:

scala

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?

like image 753
baba.kabira Avatar asked Sep 16 '26 11:09

baba.kabira


1 Answers

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.

like image 153
Kevin Wright Avatar answered Sep 18 '26 01:09

Kevin Wright



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!