更重要的是 Scala 惯用的:特质 TraitA 扩展 TraitB 或特质 TraitA { self: TraitB =>; }

发布于 2024-12-02 10:53:57 字数 293 浏览 1 评论 0原文

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

1| trait TraitA extends TraitB

2| trait TraitA { self: TraitB => }

我想在 TraitATraitB 之间划分职责,但如果没有后者,前者就无法运行。

你会如何表达这个意图?对我来说,解决方案 [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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

完美的未来在梦里 2024-12-09 10:53:57

我的偏好通常是 [1],因为正如您所说,实现者没有负担混合 TraitB(的子类型)。如果出于某种原因,希望继承TraitB中的具体实现并强制实现者在子类型中做出选择,那么也许[2]更可取。 特征B。尽管如此,[1] 也同样灵活。

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

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

更新。这是另一个细微差别,

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

有点烦人 可选限制不能将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 in TraitB and force the implementor to make a choice among sub-types of TraitB. 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,

// 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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文