加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 具有另一类自我类型的类是否有意义?

发布时间:2020-12-16 18:54:19 所属栏目:安全 来源:网络整理
导读:scala class Adefined class Ascala class B {this: A = }defined class Bscala new Bconsole:10: error: class B cannot be instantiated because it does not conformto its self-type B with A new B ^ B类设置自型类A,因此B类(或它的一个子类)具有延长类
scala> class A
defined class A

scala> class B {this: A => }
defined class B

scala> new B
<console>:10: error: class B cannot be instantiated because it does not conform
to its self-type B with A
             new B
             ^

B类设置自型类A,因此B类(或它的一个子类)具有延长类A创建B的一个实例,但是这可能在所有的,由于B的子类可以只延伸一个类(这是B类)?

所以这引出了我的问题,在任何情况下将类的自我类型声明为另一个类是否有意义?

解决方法

你认为这个定义不能导致具体的实现是正确的,因为你不能混合两个类,只有特征.所以简短的回答是’不’,或者应该是一个特征.

关于自我类型,Stackoverflow有几个问题.这两个有用的是:

> What is more Scala idiomatic: trait TraitA extends TraitB or trait TraitA { self: TraitB => }
> Difference between trait inheritance and self type annotation

在第二个问题中,Ben Lings给出了一个很好的答案,引用了以下来自Spiros Tzavellas的博客:

In conclusion,if we want to move method implementations inside traits then we risk polluting the interface of those traits with abstract methods that support the implementation of the concrete methods and are unrelated with the main responsibility of the trait. A solution to this problem is to move those abstract methods in other traits and compose the traits together using self type annotations and multiple inheritance.

例如,如果A(假设它是特征而不是现在的类!)是一个记录器.您不希望公开B公开由A混合的日志记录API.因此,您将使用自我类型而不是mixin.在B的实现中,您可以调用日志API,但是从外部看不到它.

另一方面,您可以使用以下形式的组合:

trait B {
    protected def logger: A
}

现在的区别在于

> B想要使用其功能时必须参考记录器
> B的子类型可以访问记录器
> B和A不在命名空间中竞争(例如,可以在没有冲突的情况下使用相同名称的方法)

我会说自我类型是Scala的一个相当外围的特性,在许多情况下你不需要它们,并且你有这样的选项可以在没有自我类型的情况下实现几乎相同.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读