8
votes

I am learning Scala and have a question regarding lower bound.

I have a class:

class Queue[+T] {
    def enqueue[U>:T](x : U) = new Queue[U]()
}

class Fruit
class Apple extends Fruit
class Orange extends Fruit
class Another

What I found is that, for a Queue of any type, e.g.:

    val q1 = new Queue[Fruit]

All the three lines below will pass compile

    q1.enqueue(new Apple)
    q1.enqueue(new Orange)
    q1.enqueue(new Another)

My question is: if we use lower bound to define U must be a super type of T, in the lines above, Apple is clearly not a super type of Fruit, how can it be passed to the enqueue function?

The "Another" class is not in the fruit hierachy at all, how can it be used in the enqueue function?

Please help me out with this.

Regards Kevin

2
Imagine the colon >: as an equals >=Peter Schmitz
i also had the same question. the answers given below clarified my doubt. you should accept an answer below.weima

2 Answers

13
votes

If you take a look of what your new queues return:

scala>  q1.enqueue(new Apple)
res0: Queue[Fruit] = Queue@17892d5

scala> q1.enqueue(new Orange)
res1: Queue[Fruit] = Queue@bdec44

scala> q1.enqueue(new Another)
res2: Queue[ScalaObject] = Queue@104bce3

What you said that specifically U should be a super-type of T (or T). This means Another works great because ScalaObject is the most specific super-type of both Another and Fruit.

5
votes

My question is: if we use lower bound to define U must be a super type of T, in the lines above, Apple is clearly not a super type of Fruit, how can it be passed to the enqueue function?

But new Apple is a Fruit, and Fruit is a supertype of Fruit. So in your case U is Fruit, and a Queue[Fruit] is returned. And new Another is a ScalaObject, which is also a supertype of Fruit...