在 class 中混合特征

Mixing a trait in a class

来自 'Programming In Scala',第 12 章(关于特质):

The Doubling trait has two funny things going on. The first is that it declares a superclass, IntQueue. This declaration means that the trait can only be mixed into a class that also extends IntQueue. Thus, you can mix Doubling into BasicIntQueue, but not into Rational.

但是我们可以让我们的 class 扩展任何 class 然后使用 'with' 关键字混合特征。

But we can have our class extend any class and then mixin the trait using 'with' keyword.

不,你不能。如果您尝试使用此特征:

class X extends Rational with Doubling

你会得到一个错误,因为 X 会有两个超类:来自 DoublingRationalIntQueue。书上是这么说的。

引用书中的这句话:

这个声明意味着特征只能是 混合到一个 class 中,它也扩展了 IntQueue 。因此,您可以混合 Doubling 进入 BasicIntQueue ,但不进入 Rational 。您只能将一个特征与任何其他 class 混合,该特征也继承自混合特征的超级 class。