1
votes

In Programming in Scala 2nd Edition in section 19.5 in following example

class Queue[+T] (private val leading: List[T],
      private val trailing: List[T] ) {
    def enqueue[U >: T](x: U) =
      new Queue[U](leading, x :: trailing) // ...
}

T should end up at negative position like below

def enqueue[U- >: T-](x: U-) =
          new Queue[U](leading, x :: trailing) // ...

But the book mentions that there are 2 flips

Technically, what happens is a flip occurs for lower bounds. The type parameter U is in a negative position (1 flip), while the lower bound (>: T) is in a positive position (2 flips).

How 2 flips occur here?

1

1 Answers

1
votes

In enqueue, T is not a type parameter, but a reference to a type member of the outer context. Therefore it is not correct to say "T should end up at negative position".

Perhaps you could think of the reference to T as the lower bound of U as a "method call that yields T", only it's a "type call", so T is sort of in a "return type" or covariant position.

The following sentence is important:

Intuitively, if T is a more specific type than expected (for example, Apple instead of Fruit), a call to append will still work, because U (Fruit) will still be a supertype of T (Apple).