Traits or classes with abstract type members are often used in combination with anonymous class instantiations. To illustrate this, we now look at a program which deals with a sequence buffer that refers to a list of integers:
trait Buffer {
type T
val element: T
}
abstract class SeqBuffer extends Buffer {
type U
type T <: Seq[U]
def length = element.length
}
abstract class IntSeqBuffer extends SeqBuffer {
type U = Int
}
object AbstractTypeTest1 extends App {
def newIntSeqBuf(elem1: Int, elem2: Int): IntSeqBuffer =
new IntSeqBuffer {
type T = List[U]
val element = List(elem1, elem2)
}
val buf = newIntSeqBuf(7, 8)
println("length = " + buf.length)
println("content = " + buf.element)
}
The return type of method newIntSeqBuf
refers to a specialization of trait Buffer
in which type U
is now equivalent to Int
. We have a similar type alias in the anonymous class instantiation within the body of method newIntSeqBuf
. Here we create a new instance of IntSeqBuffer
in which type
...