ВУЗ: Не указан
Категория: Не указан
Дисциплина: Не указана
Добавлен: 02.01.2026
Просмотров: 3471
Скачиваний: 0
Section 12.5 |
Chapter 12 · Traits |
268 |
An abstract IntQueue class is shown in Listing 12.6. IntQueue has a put method that adds new integers to the queue and a get method that removes and returns them. A basic implementation of IntQueue that uses an ArrayBuffer is shown in Listing 12.7.
abstract class IntQueue { def get(): Int
def put(x: Int)
}
Listing 12.6 · Abstract class IntQueue.
import scala.collection.mutable.ArrayBuffer
class BasicIntQueue extends IntQueue { private val buf = new ArrayBuffer[Int] def get() = buf.remove(0)
def put(x: Int) { buf += x }
}
Listing 12.7 · A BasicIntQueue implemented with an ArrayBuffer.
Class BasicIntQueue has a private field holding an array buffer. The get method removes an entry from one end of the buffer, while the put method adds elements to the other end. Here’s how this implementation looks when you use it:
scala> val queue = new BasicIntQueue
queue: BasicIntQueue = BasicIntQueue@24655f
scala> queue.put(10)
scala> queue.put(20)
scala> queue.get() res9: Int = 10
scala> queue.get() res10: Int = 20
So far so good. Now take a look at using traits to modify this behavior. Listing 12.8 shows a trait that doubles integers as they are put in the queue.
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index
Section 12.5 |
Chapter 12 · Traits |
269 |
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.
trait Doubling extends IntQueue {
abstract override def put(x: Int) { super.put(2 * x) }
}
Listing 12.8 · The Doubling stackable modification trait.
The second funny thing is that the trait has a super call on a method declared abstract. Such calls are illegal for normal classes, because they will certainly fail at run time. For a trait, however, such a call can actually succeed. Since super calls in a trait are dynamically bound, the super call in trait Doubling will work so long as the trait is mixed in after another trait or class that gives a concrete definition to the method.
This arrangement is frequently needed with traits that implement stackable modifications. To tell the compiler you are doing this on purpose, you must mark such methods as abstract override. This combination of modifiers is only allowed for members of traits, not classes, and it means that the trait must be mixed into some class that has a concrete definition of the method in question.
There is a lot going on with such a simple trait, isn’t there! Here’s how it looks to use the trait:
scala> class MyQueue extends BasicIntQueue with Doubling defined class MyQueue
scala> val queue = new MyQueue queue: MyQueue = MyQueue@91f017
scala> queue.put(10)
scala> queue.get() res12: Int = 20
In the first line in this interpreter session, we define class MyQueue, which extends BasicIntQueue and mixes in Doubling. We then put a 10 in the queue, but because Doubling has been mixed in, the 10 is doubled. When we get an integer from the queue, it is a 20.
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index
Section 12.5 |
Chapter 12 · Traits |
270 |
Note that MyQueue defines no new code. It simply identifies a class and mixes in a trait. In this situation, you could supply “BasicIntQueue with Doubling” directly to new instead of defining a named class. It would look as shown in Listing 12.9:
scala> val queue = new BasicIntQueue with Doubling queue: BasicIntQueue with Doubling = $anon$1@5fa12d
scala> queue.put(10)
scala> queue.get() res14: Int = 20
Listing 12.9 · Mixing in a trait when instantiating with new.
To see how to stack modifications, we need to define the other two modification traits, Incrementing and Filtering. Implementations of these traits are shown in Listing 12.10:
trait Incrementing extends IntQueue {
abstract override def put(x: Int) { super.put(x + 1) }
}
trait Filtering extends IntQueue { abstract override def put(x: Int) {
if (x >= 0) super.put(x)
}
}
Listing 12.10: Stackable modification traits Incrementing and Filtering.
Given these modifications, you can now pick and choose which ones you want for a particular queue. For example, here is a queue that both filters negative numbers and adds one to all numbers that it keeps:
scala> val queue = (new BasicIntQueue
with Incrementing with Filtering)
queue: BasicIntQueue with Incrementing with Filtering...
scala> queue.put(-1); queue.put(0); queue.put(1)
scala> queue.get() res15: Int = 1
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index
Section 12.6 |
Chapter 12 · Traits |
271 |
scala> queue.get() res16: Int = 2
The order of mixins is significant.2 The precise rules are given in the following section, but, roughly speaking, traits further to the right take effect first. When you call a method on a class with mixins, the method in the trait furthest to the right is called first. If that method calls super, it invokes the method in the next trait to its left, and so on. In the previous example, Filtering’s put is invoked first, so it removes integers that were negative to begin with. Incrementing’s put is invoked second, so it adds one to those integers that remain.
If you reverse the order, first integers will be incremented, and then the integers that are still negative will be discarded:
scala> val queue = (new BasicIntQueue
with Filtering with Incrementing)
queue: BasicIntQueue with Filtering with Incrementing...
scala> queue.put(-1); queue.put(0); queue.put(1)
scala> queue.get() res17: Int = 0
scala> queue.get() res18: Int = 1
scala> queue.get() res19: Int = 2
Overall, code written in this style gives you a great deal of flexibility. You can define sixteen different classes by mixing in these three traits in different combinations and orders. That’s a lot of flexibility for a small amount of code, so you should keep your eyes open for opportunities to arrange code as stackable modifications.
12.6 Why not multiple inheritance?
Traits are a way to inherit from multiple class-like constructs, but they differ in important ways from the multiple inheritance present in many languages. One difference is especially important: the interpretation of super. With
2Once a trait is mixed into a class, you can alternatively call it a mixin.
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index
Section 12.6 |
Chapter 12 · Traits |
272 |
multiple inheritance, the method called by a super call can be determined right where the call appears. With traits, the method called is determined by a linearization of the classes and traits that are mixed into a class. This is the difference that enables the stacking of modifications described in the previous section.
Before looking at linearization, take a moment to consider how to stack modifications in a language with traditional multiple inheritance. Imagine the following code, but this time interpreted as multiple inheritance instead of trait mixin:
// Multiple |
inheritance |
thought experiment |
val q = new |
BasicIntQueue with Incrementing with Doubling |
|
q.put(42) |
// which put |
would be called? |
The first question is, which put method would get invoked by this call? Perhaps the rule would be that the last superclass wins, in which case Doubling would get called. Doubling would double its argument and call super.put, and that would be it. No incrementing would happen! Likewise, if the rule were that the first superclass wins, the resulting queue would increment integers but not double them. Thus neither ordering would work.
You might also entertain the possibility of allowing programmers to identify exactly which superclass method they want when they say super. For example, imagine the following Scala-like code, in which super appears to be explicitly invoked on both Incrementing and Doubling:
// Multiple inheritance thought experiment trait MyQueue extends BasicIntQueue
with Incrementing with Doubling {
def put(x: Int) {
Incrementing.super.put(x) // (Not real Scala) Doubling.super.put(x)
}
}
This approach would give us new problems. The verbosity of this attempt is the least of its problems. What would happen is that the base class’s put method would get called twice—once with an incremented value and once with a doubled value, but neither time with an incremented, doubled value.
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index
Section 12.6 |
Chapter 12 · Traits |
273 |
There is simply no good solution to this problem using multiple inheritance. You would have to back up in your design and factor the code differently. By contrast, the traits solution in Scala is straightforward. You simply mix in Incrementing and Doubling, and Scala’s special treatment of super in traits makes it all work out. Something is clearly different here from traditional multiple inheritance, but what?
As hinted previously, the answer is linearization. When you instantiate a class with new, Scala takes the class and all of its inherited classes and traits and puts them in a single, linear order. Then, whenever you call super inside one of those classes, the invoked method is the next one up the chain. If all of the methods but the last call super, the net result is stackable behavior.
The precise order of the linearization is described in the language specification. It is a little bit complicated, but the main thing you need to know is that, in any linearization, a class is always linearized before all of its superclasses and mixed in traits. Thus, when you write a method that calls super, that method is definitely modifying the behavior of the superclasses and mixed in traits, not the other way around.
Note
The remainder of this section describes the details of linearization. You can safely skip the rest of this section if you are not interested in understanding those details right now.
The main properties of Scala’s linearization are illustrated by the following example: Say you have a class Cat, which inherits from a superclass
Animal and two traits Furry and FourLegged. FourLegged extends in turn another trait HasLegs:
class Animal
trait Furry extends Animal trait HasLegs extends Animal
trait FourLegged extends HasLegs
class Cat extends Animal with Furry with FourLegged
Class Cat’s inheritance hierarchy and linearization are shown in Figure 12.1. Inheritance is indicated using traditional UML notation:3 arrows with white, triangular arrowheads indicate inheritance, with the arrowhead
3Rumbaugh, et. al., The Unified Modeling Language Reference Manual. [Rum04]
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index
Section 12.6 |
Chapter 12 · Traits |
274 |
Any
AnyRef
Animal HasLegs
Furry FourLegged
Cat
Figure 12.1 · Inheritance hierarchy and linearization of class Cat.
pointing to the supertype. The arrows with darkened, non-triangular arrowheads depict linearization. The darkened arrowheads point in the direction in which super calls will be resolved.
The linearization of Cat is computed from back to front as follows. The last part of the linearization of Cat is the linearization of its superclass, Animal. This linearization is copied over without any changes. (The linearization of each of these types is shown in Table 12.1 on page 275.) Because Animal doesn’t explicitly extend a superclass or mix in any supertraits, it by default extends AnyRef, which extends Any. Animal’s linearization, therefore, looks like:
Animal AnyRef Any
The second to last part is the linearization of the first mixin, trait Furry, but all classes that are already in the linearization of Animal are left out now, so that each class appears only once in Cat’s linearization. The result is:
Furry Animal AnyRef Any
This is preceded by the linearization of FourLegged, where again any classes that have already been copied in the linearizations of the superclass or the first mixin are left out:
FourLegged HasLegs Furry Animal AnyRef Any
Finally, the first class in the linearization of Cat is Cat itself:
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index