什么是Scala惯用语:特质TraitA扩展TraitB或特质TraitA {self:TraitB => } [英] What is more Scala idiomatic: trait TraitA extends TraitB or trait TraitA { self: TraitB => }

查看:181
本文介绍了什么是Scala惯用语:特质TraitA扩展TraitB或特质TraitA {self:TraitB => }的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了继承方面,以下类模板之间是否存在差异:

Apart from the inheritance aspect, is there a difference between the following class templates:

1| trait TraitA extends TraitB

2| trait TraitA { self: TraitB => }

我想在 TraitA 和 TraitB 但前者在没有后者的情况下无法运作。

I would like to split responsibilities between TraitA and TraitB but the former cannot function without the latter.

您如何表达此意图? 对我而言,解决方案[2]将是更自然的方法。但是我不想把实施者的负担混合在一起需要混合的东西。

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.

推荐答案

我的偏好一般[1]因为,正如你所说的那样,实现者没有负担混合(子类型) TraitB 。如果由于某种原因,希望继承 TraitB 中的具体实现并强制实现者创建一个在 TraitB 的子类型中进行选择。尽管如此,[1]同样灵活。

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 in TraitB and force the implementor to make a choice among sub-types of TraitB. Still, [1] is just as flexible.

我倾向于仅在必要时使用[2],例如当类型不是已知的类或特征时,

I tend to use [2] only where necessary, such as when the type isn't a known class or trait,

// Here, Matrix cannot extend type parameter Repr
trait Matrix[+Repr <: Matrix[Repr]] { self: Repr =>
  ...
}

更新。这是另一个小的差异,

Update. Here's another minor difference,

trait B
trait A { self: B => }
def g(ab: A): B = ab // Type mismatch: found A, required B

有点讨厌 可选限制无法使用 A 作为 B ,即使该类型已合并。

It's a little annoying an optional restriction not to be able to use A as a B, even though the type is incorporated.

这篇关于什么是Scala惯用语:特质TraitA扩展TraitB或特质TraitA {self:TraitB =&gt; }的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆