About the lower bound in Scala

I study Scala and ask a question regarding the 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 

I found that for a queue of any type, for example:

  val q1 = new Queue[Fruit] 

All three lines below will pass the compilation

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

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

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

Please help me with this.

Relations Kevin

+8
scala
source share
2 answers

If you look at how 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 did you say that exactly U should be a supertype of T (or T). This means that Friend works fine because ScalaObject is the most specific supertype of both Other and Fruit.

+12
source share

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

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

+5
source share

All Articles