更重要的是 Scala 惯用的:特质 TraitA 扩展 TraitB 或特质 TraitA { self: TraitB =>; }
除了继承方面之外,以下类模板之间是否存在差异:
1| trait TraitA extends TraitB
2| trait TraitA { self: TraitB => }
我想在 TraitA
和 TraitB
之间划分职责,但如果没有后者,前者就无法运行。
你会如何表达这个意图?对我来说,解决方案 [2] 将是更自然的方法。然而,无论如何,我不想给实施者带来混合需要混合的负担。
Apart from the inheritance aspect, is there a difference between the following class templates:
1| trait TraitA extends TraitB
2| trait TraitA { self: TraitB => }
I would like to split responsibilities between TraitA
and TraitB
but the former cannot function without the latter.
How would you express this intent? To me solution [2] would be the more natural approach. However I do not want to put the burden on implementers mixing in what needs to be mixed in anyway.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的偏好通常是 [1],因为正如您所说,实现者没有负担混合
TraitB
(的子类型)。如果出于某种原因,希望不继承TraitB
中的具体实现并强制实现者在子类型中做出选择,那么也许[2]更可取。特征B
。尽管如此,[1] 也同样灵活。我倾向于仅在必要时使用 [2],例如当类型不是已知的类或特征时,
更新。这是另一个细微差别,
有点烦人可选限制不能将A
用作B
,即使类型已合并。My preference is generally [1] because, as you say, the implementor is not burdened to mix in (a sub-type of)
TraitB
. Perhaps [2] is preferable if, for some reason, it is desirable not to inherit the concrete implementations inTraitB
and force the implementor to make a choice among sub-types ofTraitB
. Still, [1] is just as flexible.I tend to use [2] only where necessary, such as when the type isn't a known class or trait,
Update. Here's another minor difference,
It's
a little annoyingan optional restriction not to be able to useA
as aB
, even though the type is incorporated.