Do you want BuboFlash to help you learning these things? Or do you want to add or correct something? Click here to log in or create user.



#scala

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 Uis 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 T refers to List[Int].

If you want to change selection, open document below and click on "Move attachment"

Abstract Types - Scala Documentation
which allows us to store only sequences in the buffer by stating that type T has to be a subtype of Seq[U] for a new abstract type U: abstract class SeqBuffer extends Buffer { type U type T <: Seq[U] def length = element.length } <span>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: 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 instantiat


Summary

statusnot read reprioritisations
last reprioritisation on suggested re-reading day
started reading on finished reading on

Details



Discussion

Do you want to join discussion? Click here to log in or create user.