Here is an example from the stairway book:
object Example {
class Queue[+T] private (
private[this] var leading: List[T],
private [this] var trailing: List[T]
) {
private def mirror: Unit = {
if(leading.isEmpty) {
while(!trailing.isEmpty) {
leading = trailing.head :: leading
trailing = trailing.tail
}
}
}
// cannot resolve symbol U
def this[U >: T](xs: U*) = this(xs.toList, Nil)
// Covariant type T occurs in contra-variant position
def this(xs: T*) = this(xs.toList, Nil)
def head: T = {
mirror
leading.head
}
def tail: Queue[T] = {
mirror
new Queue(leading.tail, trailing)
}
def enqueue[U >: T](x: U) = new Queue[U](leading, x :: trailing)
def size = leading.size + trailing.size
}
}
I added these lines:
// cannot resolve symbol U
def this[U >: T](xs: U*) = this(xs.toList, Nil)
// Covariant type T occurs in contra-variant position
def this(xs: T*) = this(xs.toList, Nil)
because I need some public constructors to create new Queues. But each of these constructors has its problems (see the comments). What can be done to solve them?
Update
A constructor with no parameters seems to compile fine:
def this() = this(Nil, Nil)