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, eg:
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
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.
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
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.