Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About lower bound in Scala

Tags:

scala

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

like image 230
Kevin Avatar asked Mar 23 '12 07:03

Kevin


People also ask

What is lower bound with example?

A value that is less than or equal to every element of a set of data. Example: in {3,5,11,20,22} 3 is a lower bound.

Which is the lower bound?

Definition of lower boundan element less than or equal to all the elements in a given set: The numbers 0 and 1 are lower bounds of the set consisting of 1, 2, and 3.

What does a lower bound number mean?

The lower bound is the smallest value that would round up to the estimated value. The upper bound is the smallest value that would round up to the next estimated value. For example, a mass of 70 kg, rounded to the nearest 10 kg, has a lower bound of 65 kg, because 65 kg is the smallest mass that rounds to 70 kg.

What is the lower bound of a function?

A lower bound is any value that is less than or equal to all possible values of the function. The greatest lower bound (also known as the infimum) is the greatest of all lower bounds. Similarly the are upper bounds (plural) and the least upper bound (aka the supremum).


2 Answers

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.

like image 63
thoredge Avatar answered Nov 15 '22 23:11

thoredge


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...

like image 33
Alexey Romanov Avatar answered Nov 15 '22 22:11

Alexey Romanov