Professional Documents
Culture Documents
1
the requirement that it can only be mixed into classes
that subclass Buffer. But the functionality provided
by IterableBuffer only depends on the existence of an
elements method. Scala makes it possible to express this
in the following form:
trait Iterable[T] {
def elements: Iterator[T];
def forall(p: T => Boolean): Boolean = {
val it = elements; var res = true;
while (res && it.hasNext) { res = p(it.next) }
res
}
def exists(p: T => Boolean): Boolean = {
val it = elements; var res = false;
while (!res && it.hasNext) { res = p(it.next) }
res
}
}
Trait Iterable de_nes methods forall and exists as before,
but defers the de_nition of method elements _ it
is abstract in the terminology of Java. As opposed to
class IterableBuffer, this trait can be mixed into all
classes. If Iterable is mixed into a class without a concrete
elements method, then the resulting class will have a deferred
elements method, otherwise, the concrete method will
implement the deferred method mentioned in trait Iterable.
Thus, concrete methods always override abstract ones in
mixin-class compositions. This principle is exploited in the
following alternative de_nition of class IterableBuffer:
class IterableBuffer[T] extends Buffer[T]
with Iterable[T];