在运行时向类添加特定特征
我有一些方法的特征“Foo”。我想将这种特质融入到任何班级中。但我不想写一些像
val b = new Bar with Foo
我需要像我刚刚通过一个类并且它与 Foo 混合的东西。我只想与此特征混合,即所有类都应仅与 Foo 特征混合。
val b = new Factory(Bar) //Factory returns instance with trait Foo
我发现了这篇帖子,但我不相信。
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当前最好的解决方案是实现
Foo
,如下所示:然后将其用作
对于
Foo
和Bar
之间共享的任何方法名称,将使用Foo
中的版本(与 mixin 中的重载一样)。对于任何其他方法,将使用Bar
上的变体。该技术并不完美,
Bar
中的方法只会调用Bar
中定义的其他方法,而绝不会“重载”Foo
中定义的方法。否则,它非常接近您的需求。The current best solution is to implement
Foo
something like this:Then use it as
For any method names that are shared between
Foo
andBar
, the version inFoo
will be used (as with overloading in a mixin). Any other methods, the variant onBar
will be used.The technique isn't perfect, methods in
Bar
will only ever call other methods defined inBar
, and never "overloads" defined inFoo
. Otherwise, it's pretty close to your needs.