Scala Bounds Intersection

104 Views Asked by At

I have learned about Lower and Upper Bound in Scala. I know how to deal with them separately but what happens if we take them together i.e. say A >: B <: C My question is based on this problem:

trait Thing
class Vehicle extends Thing
class Car extends Vehicle
class Jeep extends Car
class Coupe extends Car
class Motorcycle extends Vehicle
class Bicycle extends Vehicle
class Tricycle extends Bicycle

and suppose we declare

class Parking[A >: Bicycle <: Vehicle](val plaza: A)

So from A>: Bicycle we can infer A can have type Bicycle, Vehicle, and Thing and from A<: Vehicle we can infer that A can have any type except Thing

so from above statement can we infer that A can have only types Bicycle, Vehicle, and Thing by using Mathematical Intersection Property? So I found this working ,according to Liskov's principle

new Parking(new Tricycle)

but why the following also works?

new Parking(new Coupe)

I'm new to this, so please guide me rather than marking more duplicate and closing this.

1

There are 1 best solutions below

13
On

No, this won't throw an error.

new Tricycle can be of types Tricycle, Bicycle, Vehicle, Thing, AnyRef, Any.

new Parking[Tricycle](new Tricycle) doesn't compile but new Parking[Vehicle](new Tricycle), new Parking[Bicycle](new Tricycle) do.

In new Parking(new Tricycle) A is inferred to be Bicycle, so it doesn't throw an error.


new Coupe can be of types Coupe, Car, Vehicle, Thing, AnyRef, Any. Among them it's Vehicle that solves the inequality A >: Bicycle <: Vehicle.