特质继承和自我类型注释之间的区别 [英] Difference between trait inheritance and self type annotation

查看:100
本文介绍了特质继承和自我类型注释之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中,我已经看到了结构

In Scala, I've seen the constructs

trait T extends S

trait T { this: S =>

用于实现类似的目的(即,必须在创建实例之前定义S中的抽象方法).它们之间有什么区别?为什么您要在另一个上使用?

used to achieve similar things (namely that the abstract methods in S must be defined before an instance may be created). What's the difference between them? Why would you use one over the other?

推荐答案

我将使用自类型进行依赖项管理:此特征需要混入另一个特征.我将使用继承来完善另一个特征或界面.

I'd use self-types for dependency-management: This trait requires another trait to be mixed in. And I'd use inheritance to refine another trait or interface.

仅作为示例:

trait FooService

trait FooRemoting { this : FooService => }
trait FooPersistence { this : FooService => }

object Services extends FooService with FooRemoting with FooPersistence

现在,如果FooRemoting和FooPersistence都将从FooService继承,并且FooService具有成员和方法,那么Services的外观如何?

Now, if FooRemoting and FooPersistence both would have inherited from FooService, and FooService has members and methods, how would Services look like?

对于继承,我们会有类似的东西:

Whereas for inheritance, we'd have something like:

trait Iterator[T] {
  def hasNext : boolean
  def next : T
}

trait InfiniteIterator[T] extends Iterator[T] {
  def hasNext = true
}

这篇关于特质继承和自我类型注释之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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