Adding a specific class to a class at runtime

I have the "Foo" trait with some methods. I want to mix this trait with any class. But I do not want to write something like

val b = new Bar with Foo

I need something like where I just went through the class and it mixes with Foo. I want to mix with this attribute only ie, it is fixed that all classes should be mixed only with the Foo attribute.

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

I found this post , but I'm not sure.

Is something like this possible in scala?

+3
source share
1 answer

Currently, the best solution is to implement Foosomething like this:

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

Then use it like

val foo = Foo(myBar)

, Foo Bar, Foo ( mixin). , Bar.

, Bar , Bar, "", Foo. .

+4

Source: https://habr.com/ru/post/1775824/


All Articles