Scala的特质不是真正的特质吗? [英] How are Scala's traits not really traits?

查看:71
本文介绍了Scala的特质不是真正的特质吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近有人告诉我,Scala的特征不是真实"特征,它们实际上只是mixins.不幸的是,我没有机会问他为什么.有人知道他的意思吗?

Someone recently told me that Scala's traits aren't "true" traits, and that they were really just mixins. Unfortunately, I didn't get the opportunity to ask him why. Does anyone have an idea what he meant?

修改: 作为特质"的定义,我一直在引用NathanaelSchärli的论文和概念论文介绍特质.大多数混合和/或多重继承实现中似乎缺少的一项关键功能是,在导入方法时可以重命名方法,以避免冲突/歧义. Scala可以做到吗?

As a definition of "traits," I have been referring to Nathanael Schärli’s dissertation and concept paper introducing traits. One key feature that seems to be missing from most mixin and/or multiple inheritance implementations is the ability to rename methods when you import them to avoid collision/ambiguity. Can Scala do that?

推荐答案

mixin和trait之间的一个关键区别是mixins有字段,而trait没有.用原始论文的特质来解释:

One key different between mixins and traits is that mixins have fields, whereas traits do not. Paraphrasing from the original paper, a trait:

  • 提供实现行为的方法
  • 需要参数化提供的行为的方法
  • 不指定或访问任何字段
  • 对称组成
  • 可以嵌套,等同于扁平化特征

乍一看,第三点似乎在Scala实现中被破坏了.但是,特征只能访问公共字段,这些公共字段受隐式getter和setter的保护.论文接着描述了这对于特质的实现是可以接受的.

At first glance the third point looks like it is broken in the Scala implementation. However, traits can only access public fields, which are protected by implicit getters and setters. The paper goes on to describe that this is acceptable for the implementation of traits.

您指出,特征的一个关键特征是在导入方法时可以重命名方法.鉴于JVM的限制,这是不可能的.可以在这里找到相关的讨论: http ://scala-programming-language.1934581.n4.nabble.com/Trait-method-aliasing-td2322026.html ,尤其是David Pollak的帖子.

You point out that a key feature of traits is that methods can be renamed when you import them. This is not possible given the constraints of the JVM. A coherent discussion of this can be found here: http://scala-programming-language.1934581.n4.nabble.com/Trait-method-aliasing-td2322026.html, particularly the posts by David Pollak.

最后,我对您的一般问题的回答是有点".详细地说,Scala特性不是本文定义的严格特性,但它们也不严格是mixins.无论哪种方式,最好像它们一样使用它们,并遵守其设计原则.

Finally, my answer to your general question is "sort of". To elaborate, whilst Scala traits are not strictly traits as defined by the paper, they are not strictly mixins either. Either way, it is probably best to use them like they were traits and keep to their design principles.

  • 将它们保持较小,以便重复使用.
  • 指定行为而不是状态.

这篇关于Scala的特质不是真正的特质吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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